Exceptions in Java provide a consistent mechanism for identifying and responding to error conditions. Effective exception handling will make your programs more robust and easier to debug. Exceptions are a tremendous debugging aid because they help answer these three questions:
What went wrong?
Where did it go wrong?
Why did it go wrong?
When exceptions are used effectively, what is answered by the type of exception thrown, where is answered by the exception stack trace, and why is answered by the exception message. If you find your exceptions aren't answering all three questions, chances are they aren't being used effectively. Three rules will help you make the best use of exceptions when debugging your programs. These rules are: be specific, throw early, and catch late.
To illustrate these rules of effective exception handling, this article discusses a fictional personal finance manager called JCheckbook. JCheckbook can be used to record and track bank account activity, such as deposits, withdrawals, and checks written. The initial version of JCheckbook runs as a desktop application, but future plans call for an HTML client and a client/server applet implementation.
Be Specific
Java defines an exception class hierarchy, starting with Throwable, which is extended by Error and Exception, which is then extended by RuntimeException. These are illustrated in Figure 1.
Figure 1. Java exception hierarchy
These four classes are generic and they don't provide much information about what went wrong. While it is legal to instantiate any of these classes (e.g., new Throwable()), it is best to think of them as abstract base classes, and work with more specific subclasses. Java provides a substantial number of exception subclasses, and you may define your own exception classes for additional specificity.
For example, the java.io package defines the IOException subclass, which extends Exception. Even more specific are FileNotFoundException, EOFException, and ObjectStreamException, all subclasses of IOException. Each one describes a particular type of I/O-related failure: a missing file, an unexpected end-of-file, or a corrupted serialized object stream, respectively. The more specific the exception, the better our program answers what went wrong.
It is important to be specific when catching exceptions, as well. For example, JCheckbook may respond to a FileNotFoundException by asking the user for a different file name. In the case of an EOFException, it may be able to continue with just the information it was able to read before the exception was thrown. If an ObjectStreamException is thrown, the program may need to inform the user that the file has been corrupted, and that a backup or a different file needs to be used.
Java makes it fairly easy to be specific when catching exceptions because we can specify multiple catch blocks for a single try block, each handling a different type of exception in an appropriate manner.
File prefsFile = new File(prefsFilename);
try
{
readPreferences(prefsFile);
}
catch (FileNotFoundException e)
{
// alert the user that the specified file
// does not exist
}
catch (EOFException e)
{
// alert the user that the end of the file
// was reached
}
catch (ObjectStreamException e)
{
// alert the user that the file is corrupted
}
catch (IOException e)
{
// alert the user that some other I/O
// error occurred
}
JCheckbook uses multiple catch blocks in order to provide the user with specific information about the type of exception that was caught. For instance, if a FileNotFoundException was caught, it can instruct the user to specify a different file. The extra coding effort of multiple catch blocks may be an unnecessary burden in some cases, but in this example, it does help the program respond in a more user-friendly manner.
Should an IOException other than those specified by the first three catch blocks be thrown, the last catch block will handle it by presenting the user with a somewhat more generic error message. This way, the program can provide specific information when possible, but still handle the general case should an unanticipated file-related exception "slip by."
Sometimes, developers will catch a generic Exception and then display the exception class name or stack trace, in order to "be specific." Don't do this. Seeing java.io.EOFException or a stack trace printed to the screen is likely to confuse, rather than help, the user. Catch specific exceptions and provide the user with specific information in English (or some other human language). Do, however, include the exception stack trace in your log file. Exceptions and stack traces are meant as an aid to the developer, not to the end user.
Finally, notice that instead of catching the exception in the readPreferences() method, JCheckbook defers catching and handling the exception until it reaches the user interface level, where it can alert the user with a dialog box or in some other fashion. This is what is meant by "catch late," as will be discussed later in this article.
Throw Early
The exception stack trace helps pinpoint where an exception occurred by showing us the exact sequence of method calls that lead to the exception, along with the class name, method name, source code filename, and line number for each of these method calls. Consider the stack trace below:
java.lang.NullPointerException
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:103)
at jcheckbook.JCheckbook.readPreferences(JCheckbook.java:225)
at jcheckbook.JCheckbook.startup(JCheckbook.java:116)
at jcheckbook.JCheckbook.<init>(JCheckbook.java:27)
at jcheckbook.JCheckbook.main(JCheckbook.java:318)
This shows that the open() method of the FileInputStream class threw a NullPointerException. But notice that FileInputStream.close() is part of the standard Java class library. It is much more likely that the problem that is causing the exception to be thrown is within our own code, rather than the Java API. So the problem must have occurred in one of the preceding methods, which fortunately are also displayed in the stack trace.
What is not so fortunate is that NullPointerException is one of the least informative (and most frequently encountered and frustrating) exceptions in Java. It doesn't tell us what we really want to know: exactly what is null. Also, we have to backtrack a few steps to find out where the error originated.
By stepping backwards through the stack trace and investigating our code, we determine that the error was caused by passing a null filename parameter to the readPreferences() method. Since readPreferences() knows it cannot proceed with a null filename, it checks for this condition immediately:
public void readPreferences(String filename)
throws IllegalArgumentException
{
if (filename == null)
{
throw new IllegalArgumentException
("filename is null");
} //if
//...perform other operations...
InputStream in = new FileInputStream(filename);
//...read the preferences file...
}
By throwing an exception early (also known as "failing fast"), the exception becomes both more specific and more accurate. The stack trace immediately shows what went wrong (an illegal argument value was supplied), why this is an error (null is not allowed for filename), and where the error occurred (early in the readPreferences() method). This keeps our stack trace honest:
java.lang.IllegalArgumentException: filename is null
at jcheckbook.JCheckbook.readPreferences(JCheckbook.java:207)
at jcheckbook.JCheckbook.startup(JCheckbook.java:116)
at jcheckbook.JCheckbook.<init>(JCheckbook.java:27)
at jcheckbook.JCheckbook.main(JCheckbook.java:318)
In addition, the inclusion of an exception message ("filename is null") makes the exception more informative by answering specifically what was null, an answer we don't get from the NullPointerException thrown by the earlier version of our code.
Failing fast by throwing exceptions as soon as an error is detected can eliminate the need to construct objects or open resources, such as files or network connections, that won't be needed. The clean-up effort associated with opening these resources is also eliminated.
Catch Late
A common mistake of many Java developers, both new and experienced, is to catch an exception before the program can handle it in an appropriate manner. The Java compiler reinforces this behavior by insisting that checked exceptions either be caught or declared. The natural tendency is to immediately wrap the code in a try block and catch the exception to stop the compile from reporting errors.
The question is, what to do with an exception after it is caught? The absolute worst thing to do is nothing. An empty catch block swallows the exception, and all information about what, where, and why something went wrong is lost forever. Logging the exception is slightly better, since there is at least a record of the exception. But we can hardly expect that the user will read or even understand the log file and stack trace. It is not appropriate for readPreferences() to display a dialog with an error message, because while JCheckbook currently runs as a desktop application, we also plan to make it an HTML-based web application. In that case, displaying an error dialog is not an option. Also, in both the HTML and the client/server versions, the preferences would be read on the server, but the error needs to be displayed in the web browser or on the client. The readPreferences() method should be designed with these future needs in mind. Proper separation of user interface code from program logic increases the reusability of our code.
Catching an exception too early, before it can properly be handled, often leads to further errors and exceptions. For example, had the readPreferences() method shown earlier immediately caught and logged the FileNotFoundException that could be thrown while calling the FileInputStream constructor, the code would look something like this:
public void readPreferences(String filename)
{
//...
InputStream in = null;
// DO NOT DO THIS!!!
try
{
in = new FileInputStream(filename);
}
catch (FileNotFoundException e)
{
logger.log(e);
}
in.read(...);
//...
}
This code catches FileNotFoundException, when it really cannot do anything to recover from the error. If the file is not found, the rest of the method certainly cannot read from the file. What would happen should readPreferences() be called with the name of file that doesn't exist? Sure, the FileNotFoundException would be logged, and if we happened to be looking at the log file at the time, we'd be aware of this. But what happens when the program tries to read data from the file? Since the file doesn't exist, in is null, and a NullPointerException gets thrown.
When debugging a program, instinct tells us to look at the latest information in the log. That's going to be the NullPointerException, dreaded because it is so unspecific. The stack trace lies, not only about what went wrong (the real error is a FileNotFoundException, not a NullPointerException), but also about where the error originated. The problem occurred several lines of code away from where the NullPointerException was thrown, and it could have easily been several method calls and classes removed. We end up wasting time chasing red herrings that distract our attention from the true source of the error. It is not until we scroll back in the log file that we see what actually caused the program to malfunction.
What should readPreferences() do instead of catching the exceptions? It may seem counterintuitive, but often the best approach is to simply let it go; don't catch the exception immediately. Leave that responsibility up to the code that calls readPreferences(). Let that code determine the appropriate way to handle a missing preferences file, which could mean prompting the user for another file, using default values, or, if no other approach works, alerting the user of the problem and exiting the application.
The way to pass responsibility for handling exceptions further up the call chain is to declare the exception in the throws clause of the method. When declaring which exceptions may be thrown, remember to be as specific as possible. This serves to document what types of exceptions a program calling your method should anticipate and be ready to handle. For example, the "catch late" version of the readPreferences() method would look like this:
public void readPreferences(String filename)
throws IllegalArgumentException,
FileNotFoundException, IOException
{
if (filename == null)
{
throw new IllegalArgumentException
("filename is null");
} //if
//...
InputStream in = new FileInputStream(filename);
//...
}
Technically, the only exception we need to declare is IOException, but we document our code by declaring that the method may specifically throw a FileNotFoundException. IllegalArgumentException need not be declared, because it is an unchecked exception (a subclass of RuntimeException). Still, including it serves to document our code (the exceptions should also be noted in the JavaDocs for the method).
Of course, eventually, your program needs to catch exceptions, or it may terminate unexpectedly. But the trick is to catch exceptions at the proper layer, where your program can either meaningfully recover from the exception and continue without causing further errors, or provide the user with specific information, including instructions on how to recover from the error. When it is not practical for a method to do either of these, simply let the exception go so it can be caught later on and handled at the appropriate level.
Conclusion
Experienced developers know that the hardest part of debugging usually is not fixing the bug, but finding where in the volumes of code the bug hides. By following the three rules in this article, you can help exceptions help you track down and eradicate bugs and make your programs more robust and user-friendly.
Jim Cushing began his Java career in 1997 while working at a small Gainesville, FL company and attending the University of Florida.
More thoughts
2003-12-12 07:08:31 ljnelson
[Reply | View]
I have a weblog post on this subject, if anyone is interested. Briefly, I try to explain why catching early and copious wrapping is a good thing--it leads to better messages and simpler archaeological expeditions when you need to figure out what went wrong.
"Beware the dangers of generic exceptions"
http://www.javaworld.com/javaworld/jw-10-2003/jw-1003-generics.html
Don't forget good messages and thinking about how to handle loops.
2003-12-08 20:10:52 emeade
[Reply | View]
Exception messages targeted for users not developers.
Assume that some end user will be up at 2:00AM trying to meet some deadline when this exception is encountered. Give her a chance and
include filenames, URIs<a/>, classnames, or whatever you have that could help. Personally I think Jakarta's Ant does a great job of giving helpful error messages.
Looping through objects and calling methods that can throw exceptions can also be a challenge. Should one failure cause everything to stop?
Rethrowing exceptions is not the best idea....
2003-12-05 09:30:45 krage
[Reply | View]
I have experimented with a few aproaches with regards to handling exceptions and came to conclusions that
rethrowing an exception is not a good idea. Why ? because you are loosing context information available in catch() clause. The exception being rethrown contains info about context in the lower layer of your application but it may not be enough to restore the whole sequence of event. For example, you are doing jdbc call and getting SQLException. You should not rethrow it because it doesn't contain all the information about parameters of the call. As soon as you leave catch(SQLEXception ex) block you gonna loose that "context". So, I ususaly have a dedicated Exception class for each layer. The constructor takes a Throwable from the lower layer and context from the current layer. This way you do not even have to log the exception on the lower layers.
think what happens with you application if all heap memory is gone ? Any "new" statement will throws a subclass of Error. So, any mission critical code must be surrounded by at least catch(Throwable ex). If you decide to put catch(Exception ex) you must have a very good reason why it is not Throwable...
Every rule has an exception*
2003-12-09 13:46:58 jimothy
[Reply | View]
Like any rule, these rules may be broken when there is a good reason for doing so, and when the rule-breaker is aware of the consequences.
My observation is the vast majority of programmers (that I have worked with) misunderstand effective exception handling. They catch exceptions much too soon (right where the compiler complains about it), use generic catch (Exception e) blocks, and either ignore or do nothing more than log the error.
I offer these rules in hope of breaking those habits. Once you've gained enough understanding of exceptions in Java to debate the rules (as you have), you're qualified to break them (with care) when you see fit, because you do understand the consequences. But the average programmer may not, and for them, it is important for them to be aware of these rules.
Thanks for your feedback. It's interesting that with all that has been written on Java exceptions, there's always new insight available.
According to the Javadocs, "An Error...indicates serious problems that a reasonable application should not try to catch."
Catching Error or Throwable is dangerous. For example, if you do catch an OutOfMemoryError, what are you going to do about it? Trying to recover could lead to further OutOfMemoryErrors.
Not, reasonable application SHOULD catch it
2003-12-05 11:16:04 krage
[Reply | View]
... particularly mission critical.
OutOfMemoryError often happens when the application is trying to allocate a lot of objects or instance in deserialization, but the whole process can be rolled back by the releasing the created objects - just set referenrce to null and gc will help you to recover.
Besides, you still can do some other things like notifing your sa.
Not, reasonable application SHOULD catch it
2003-12-05 13:29:09 jimothy
[Reply | View]
My point was, any action to recover from or report an OutOfMemoryError (such as notifying the sysadmin) could also result in an OoME.
I suppose there's no harm trying. But do keep in mind that the time between setting a reference to null and that reference being garbage collected is indeterminant.
Not, reasonable application SHOULD catch it
2003-12-05 17:24:59 krage
[Reply | View]
Most time only allocation of a new object will result in a new OutOfMem. exception. You can still run any code which manipulates already existing objects. As of indeterministic nature of GC - yes, this is true, but there is an exception. If there is no memory available it WILL start collecting garbage BEFORE throwing another OutOfMem. exception.
Another thing is when you have catched it then the context in which it was thrown is already destroyed and the memory is actually available.
Not, reasonable application SHOULD catch it
2007-11-06 14:01:42 zolyfarkas
[Reply | View]
OOM can be thrown in the thread that is not actually causing the memory exhaustion. This makes recovery from a OOM almost impossible.
OOM is best handled by running VM with: -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DUMPS} -XX:OnOutOfMemoryError="kill -9 %p"
An endless war...
2003-12-05 00:30:25 bitog
[Reply | View]
Good article... but a consideration:
proliferation of "throws" clauses tend to be a noise to developers.
I'm used to catch early specific exceptions, log them as much specific I can, and then re-throw a RuntimeException.
I can catch them later, displaying a message in a UI-dependent way, looking also to the exception cause (getCause() method)
For example:
public void aMethod(){
...
try{
...
...
}catch (SQLException s){
myLog.log("database errror");
throw new RuntimeException(s);
}catch (FileNotFoundException f){
myLog.log("wrong file name");
throw new RuntimeException(f);
}... and so on
}finally{
// release resources
}
}
What's your opinion?
Thanks
An endless war...
2003-12-05 05:55:36 jimothy
[Reply | View]
Overall, I agree. Declaring checked exceptions has two main problems: First, it does get awkward as they proliferate, and second, they constitute an abstraction leak, as they reveal implementation details. Wrapping exceptions addresses both these problems.
I deferred discussing these issues in order to keep the scope of the article in check. I'd like to do a follow up, and detail this issue there. But in the meantime, I'm uncomfortable wrapping with a RuntimeException, because it violates the "be specific rule". It also means that your catch blocks likely will either be generic (simply catching and displaying a RuntimeException) or filled with a bunch of "instanceof" operations on the cause. This can be awkward.
Also, is it necessary to log "database error" or "wrong file name"? When the re-thrown RuntimeException is caught, that information will can be logged then. See my personal article, Exception Horror Stories for comments on the dangers of double-logging.
An endless war...
2003-12-12 06:01:06 bitog
[Reply | View]
I agree on the violation of the "be specific" rule... but, if you don't write the bunch of instance of, you have to write a lot of "catch", I guess. At least, you could put the "bunch" on a UI-dependendent utility class.
In order to the double logging: the higher logger could be located in a different layer (a different log at all), so I have to log as quick as I can DB errors on the DAO layer log and UI errors (Illegal form parameters and so on) into another possible log.
In addition: when a lower RuntimeException is caught at an higher level, I'm not forced to log it, because I'm sure that it was already done. All that I want at the UI level, most of the time, is only to display an error message to the user.
It's great to talk with you on this argument .. ;)
An endless war...
2003-12-12 06:40:27 jimothy
[Reply | View]
It sounds like you've got an exception handling strategy, and that puts you ahead of a lot of people. But I am apprehensive that you say, "I have to log as quick as I can DB errors...".
How does your UI layer KNOW that an exception occurred at the DAO layer? When the "catch late" rule is violated, the rest of the program thinks that there was no error. If there's a DB error reading a DAO, the rest of the program cannot operate on that DAO (attempting to would like result in NullPointerExceptions).
Of course, I realize there are details of your program I'm missing, and it may be that you are taking care of these issues perfectly well. But strongly consider the "catch late" rule in the context of your program. Of my three rules, I'd say this is probably the most important one, and the one that is least understood.
An endless war...
2003-12-05 06:05:23 jimothy
[Reply | View]
Oops, I should say instead of wrapping in a RuntimeException, I recommend wrapping in an application or API specific exception, something like a JCheckbookResourceException (to indicate an error accessing a resource--be it the file system, an SQL database, etc.). I do plan to expound upon this in a follow up.