Java Exceptions

Recently I asked a colleague what the current orthodoxy was regarding exception handling in Java. This is not covered at all well in any of the books I have read, besides which I suspected that this was shifting ground, so asking such a dumb question was in order.

I was pointed to three documents, the official Sun position, Bruce Eckel’s post and finally this (very good) article by Brian Goetz.

Having read all this, and based on my experience, I think this is probably the sanest approach (or least insane depending on your point of view), from the article by Brian Goetz:

Rod Johnson, author of J2EE Design and Development (see Resources), which is one of the best books I’ve read on Java development, J2EE or not, takes a less radical approach. He enumerates several categories of exceptions, and identifies a strategy for each. Some exceptions are basically secondary return codes (which generally signal violation of business rules), and some are of the “something went horribly wrong” variety (such as failure to make a database connection). Johnson advocates using checked exceptions for the first category (alternative return codes), and runtime exceptions for the latter category. In the “something went horribly wrong” category, the motivation is simply to recognize the fact that no caller is going to effectively handle this exception, so it might as well get propagated all the way up the stack with the minimum of impact on the intervening code (and minimize the chance of exception swallowing).

Johnson also enumerates a middle ground, for which he asks the question, “Will only a minority of callers want to handle the problem?” For these scenarios, he also suggests using unchecked exceptions. As an example for this category, he lists JDO exceptions — most of the time, JDO exceptions indicate a condition that the caller will not want to handle, but some cases occur where specific types of exceptions might usefully be caught and handled. Rather than make the rest of the JDO-consuming classes pay for this possibility in the form of catching and rethrowing these exceptions, he suggests using unchecked exceptions here instead.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: