July
15

I’m in the process of migrating some old Java 1.3 code to Java 6 and I really didn’t like the way exceptions were handled in the code. Before rewriting things I did some research as to what are considered the “Best Practices” when it comes to Java exception handling. Although On Java’s Best Practices for Exception Handling appears to be the most popular article on the subject, I found the most useful information to come from Exception Handling: Common Problems and Best Practices with Java 1.4 (pdf) by Dr. Andreas Muller and Geoffrey Simmons, both of whom work for the German Sun Java Center.

A summary of Mueller and Simmons’ mains points would be:

  • Empty catch blocks are bad.
  • Meaningless blanket throws clauses are bad. (e.g. catch(FooException e){ throw new BahException(e.getMessage());} )
  • Losing stack information is bad, so use exception chaining.
  • Exceptions that signal an untreatable situation should be unchecked.
  • Checked exceptions signal an exception situation that might be treatable.
  • Log an exception to the logfile exactly once.
  • The right time to log an exception in Java is the latest possible.
  • By chaining exceptions you gain information content while they travel up the call stack.
  • Programming exceptions should contain as much information about the state of the system as is available (dump state of objects, session, response, request, etc.)

An immediate benefit from the article was learning how throwing unchecked exceptions for exceptions that are untreatable (such as an SQLException) can help get you out of the antipattern where you need to include a dozen types of exceptions in your method signature. It’s a bit controversial with some of my colleagues but I really think it cuts down on some of the burden that managing exceptions can create, and allows you to consolidate and deal with the exceptions at a more appropriate place.

0