Using your own exception classes in Java

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:

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:

collect as much information as possible about what has happened

write this data to some persistent media--e.g. a log file or a data base

give the user--assuming there is one--some explanatory information about what has happened

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.

Advertiser Disclosure:
Some of the products that appear on this site are from companies from which QuinStreet receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. QuinStreet does not include all companies or all types of products available in the marketplace.