How to (not) handle Java Exceptions
May 16th, 2008The last couple of days I was digging my way through OpenJDK’s AWT/Java2D/Font2D code and found a couple of antipatterns regarding Exception handling that really stole a lot of my time. I’d like to outline them and show sane alternatives that would have saved a lot of my time.
Ignoring exceptions
This is the most stupid, and frankly, the most widespread antipattern for exception handling, probably often a result of a combination of laziness and the need to handle checked exceptions:
try {
// do something
} catch (SomeCheckedException ex) {
// dunno what to do with this.
// or even worse:
// Should never happpen.
}
Really. Never ever do this. In the (possibly rare) case, that the application runs into this, it most likely ends up in an undefined state, and makes debugging a pain. (’Hey, how does the VM get out of this method without returning? Duh! A swallowed exception!’ is usually my train of thoughts) At least, print out the exception:
catch (SomeException ex) {
ex.printStackTrace();
// maybe use logger to log this.
}
If you don’t know how to handle the exception, and don’t want to just swallow it, you could wrap it into an unchecked exception or even error (depending if you think this is an exceptional or error condition):
catch (SomeException ex) {
SomeRuntimeException rte = new SomeRuntimeException();
rte.initCause(ex);
throw rte;
}
The replaced exception
I also see this pattern from time to time:
try {
// do something.
} catch (SomeException ex) {
throw new SomeOtherException(ex.getMessage());
}
This is only little more useful than swallowing the exception completely. Again, wrapping the exception properly is a much more helpful solution, as it gives the poor developer soul at least a stacktrace to work with:
catch (SomeException ex) {
SomeOtherException ex2 = new SomeOtherException(ex.getMessage());
ex2.initCause(ex);
throw ex2;
}
There are certainly more such antipatters, these are only two of them that stole a lot of my time. If you know more, please comment and add them below.







