October 25, 2008 Leave a comment
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.
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.