Using your own exception classes in Java

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

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

 

   1 
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact