Monday, August 15, 2005

Java Exception Prescription

What are truly the best practices for using Exceptions in Java? Should checked exceptions be the norm? How should the Exception classes be structured? In this posting I attempt to achieve a personal approach to using Exceptions.

In Handling Exceptions from the Sun Java Tutorial, stresses the use of checked exceptions:

If a client can reasonably be expected to recover from an exception, make it a
checked exception. If a client cannot do anything to recover from the exception,
make it an unchecked exception

Sun's view is probably the excepted wisdom. But some leading Java guys are rethinking this, like Alan Griffiths, Bruce Eckle, and Rod Johnson.

Code written using checked exceptions tends to exhibit a couple of problems: catch clauses are often stubbed out for expediency, leading to "swallowed" exceptions. Also, all calling code ends up bloating with handling for errors that the caller may not want/need to handle.

Why not let callers catch what they want, otherwise let the error propogate up the chain? Rod defines the following rule of thumb from when to use a checked exception:

Should all callers handle this problem? Is the exception essentially a second return value for the method?

For Example,

Spending limit exceeded in a processInvoice() method

I seems to me right now that this is the way to go. Basically, throw checked if the caller can and should do something about it, otherwise throw unchecked.