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 w