advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement


Tutorials : Using your own exception classes in Java :
Contents
Using your own exception classes in Java
Linking the Exception classes
New formatting routines in MyException

Using your own exception classes in Java

by Keld H. Hansen

Every application fails once in while. Even the ones built with Java, using design patterns, best practices, and a lot of good intentions. So we better prepare our applications for these situations, right? The first thing an application should do if it fails is to tell as much as possible about the error situation. For example: where exactly in the application did the error occur, what was the Java-method calling sequence, what data was being processed, and so on.

In this article I'll present a simple, systematic approach which will help Java developers implement some solid error handling in their code. The building blocks are Java's Exception-classes.

The basic stuff about Java Exceptions

I'll not go through all the details of Java's exceptions, there are lot of good books and articles about this. But a short intro might be nice as a starter.

Java uses exceptions to report severe errors. If a Java statement fails to execute, the Java VM will create a new instance of an Exception class--or subclass thereof--and then "throw" it. A program can "catch" such an exception, inspect it using its methods, and then try to do something sensible to handle the error.

By "severe errors" I refer to situations in a program which the programmer does not consider "normal". This could be a database connection that suddenly drops, an attempt to divide by zero, or anything else that is vital to the proper functioning of a program. What is NOT a severe error is for example when you get end-of-file reading a sequential file. Even if it does not occur frequently it's expected that it will occur, and you should therefore add code in your program to handle this situation.

It's a tradition in Java literature to illustrate the use of exceptions by a "division by zero" case, so why change this approach:

public float myDivide(int a, int b) {
  float r;
  try {
    r = a / b;
  }
  catch (ArithmeticException e) {
    System.out.println(e.getMessage());
    r = Float.POSITIVE_INFINITY;
  }
  return r;
}

In this code a divison by zero is caught, and the result is set to Java's value for "infinity". The example is merely to illustrate the technique. It would be simpler--and more correct--to test if "b" had the value zero before making the division.

An "ArithmeticException" is a subclass of "RuntimeException", which again is a subclass of class "Exception". All exceptions of class "Exception" or subclasses thereof--except "RuntimeException"s--must be caught. "FileNotFoundException" is not a "RuntimeException", so if you try to read a file with a statement like this

FileInputStream f = new FileInputStream("mydata.txt");

then the Java compiler would ask you to either "try-catch" "FileNotFoundException" or declare it in the throws clause of the method, like this:

public float someMethod() throws FileNotFoundException {...

Using the latter setup the caller of "someMethod" would again need to either catch this exception or to declare it in its own throws clause. If no-one catches an exception it'll end up in the "container" that runs the Java classes. This could be the Java VM, a servlet engine, or something else. The net result would be that the program stops and some error messages are written out, probably a Java-method stack trace containing the error information from the exception class which was thrown. This is indeed useful to the programmer (not to the end-user), but very often not enough to locate the problem.

When you catch an error you have some choices:

  • repair the situation so the program can continue to run normally (as in the example above)
  • throw a new exception which the caller of the failing method then must handle
  • ignore the error (not recommended!)
  • pull the emergency break by calling System.exit()--probably after having written information to log files etc.

A really useful feature is the ability to create your own exception classes. This is done by creating a subclass of class "Exception". If you detect a problem in your application you may now throw one of your own exceptions. By doing this you simplify your error handling code, since you can now handle system errors and application errors in the same, consistent way.

So much for the basics.

When things go wrong - collect data!

I'll now describe a general technique, using your own exception classes, that can be used to handle severe, non-repairable errors. This means that your application has detected a situation that can not be neglected, so what's important now is this:

  1. collect as much information as possible about what has happened
  2. write this data to some persistent media--e.g. a log file or a data base
  3. give the user--assuming there is one--some explanatory information about what has happened
  4. keep the application alive if this makes sense and you're sure that this will not introduce further damage

The reason for "1" and "2" is obvious: in order for the support people to be able to find out what went wrong, so a program bug can be fixed, and to be able to tell the user what has happened and what the consequences are, you need all the information that you can get. We have all experienced the frustration by receiving error message like "System error at unknown location". If this is all the information the support people get, then it might be impossible to locate the problem.

So how do we collect data in a systematic way?

Let's consider the general situation where your "top-level" program (which could be a servlet, a JSP-page, or any Java class) calls method "a" in class "A", which again calls method "b" in class "B", where an exception is thrown. Let's for simplicity limit the example to these three levels.

What we should do when the exception in "b" is thrown is this:

  1. let "b" catch the exception
  2. let the catch-code save all essential data in our own exception class (see the specs below) and...
  3. throw this exception
  4. let "a" catch it
  5. let the catch-code in "a" save its own essential data in a new instance of our own exception class and...
  6. throw this exception
  7. let the top-level program catch it
  8. this program should now ensure that all collected data is written to the proper log files, and
  9. give the user at the PC an understandable message of what's going on

 

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Microsoft RIA Development Center
 IBM Rational Resource Center
 Destination .NET
XML error: not well-formed (invalid token) at line 33
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Free VMware Server 2.0 Now Release Candidate
Linux Player Xandros Grabs Storied Rival Linspire
Hey Enterprise: Here Comes the 3G iPhone
MySpace Opens Profile Portability API
Microsoft Jumps Into Virtualization Fray
Eclipse Ganymede Makes It Easier for Devs
Open Source Nokia a Threat to Microsoft, Google?
Salesforce, Google Head for 2nd on Apps
HP Open Sources Unix File System for Linux
Red Hat Opens Its Network to Space

Build a Generic Histogram Generator for SQL Server
Beyond XML and JSON: YAML for Java Developers
Mastering the Windows Mobile Emulators
Avaya AE Services Provide Rapid Telephony Integration with Facebook
Featured Algorithm: Intel Threading Building Blocks: parallel_reduce
Getting Started with Windows Live Admin Center
Eight Key Practices for ASP.NET Deployment
Java ME User Interfaces: Do It with LWUIT!
Talking VPro: Transcript
Bringing Semantic Technology to the Enterprise

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM eBook: Planning a Service Oriented Architecture
IBM eBook: Choosing the Right Architecture--What It Means for You and Your Business
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Avaya Article: Using Intelligent Presence to Create Smarter Business Applications
Intel Go Parallel Article: Getting Started with TBB on Windows
Microsoft Article: 7.0, Microsoft's Lucky Version?
Avaya Article: How to Feed Data into the Avaya Event Processor
IBM Article: Developing a Software Policy for Your Organization
Microsoft Article: Managing Virtual Machines with Microsoft System Center
Intel Go Parallel Article: Intel Threading Tools and OpenMP
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Silverlight 2 App and Walkthrough: Leverage Silverlight 2 with SQL Server and XML
IBM Article: Enterprise Search--Do You Know What's Out There?
HP Demo: StorageWorks EVA4400
Microsoft Article: The Progress and Promise of Deep Zoom
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES