|Exception Handling Rules of Thumb
by Robert Bushman
Good exception handling is an important, though often overlooked aspect of software development. A small investment in better exception handling will make most software more robust and responsive. The following rules all have exceptions, but in most cases they will serve you well. These tips are written from a Java perspective, but the general ideas apply to most languages that support try/catch-based exception handling.
Be Suspicious of Long Try Blocks
Shoot for one statement per try block. This will allow a more precise catch block, tailored to the exact fault in question.
If "This Can Never Happen," Throw an Error
The catch block with the one line comment "This can never happen" is the perfect place to throw an error. Errors are unchecked and, according to the comment, it will never happen, so it costs nothing. If it does happen, you'll be happy to have the stack trace.
Catch The Specific Exception Type
Instead of catching Exception, catch the specific type that may be thrown. The intent of the catch block will be more clear, and you won't accidentally catch some other exception you weren't expecting.
If You Catch Throwable or Error, Do So at The Top
Errors typically mean something serious went wrong. Catch specific errors if they are recoverable, but typically catching the generic Throwable or Error should happen near the entry point of the program, if at all.
Throw Specific Exception Types
Throwing a generic Exception does not communicate the nature of the problem. If there is not a specific exception type for the condition in question, write a new one.
Use Meaningful Exception Messages
When you throw an exception, clearly state what went wrong and how the invoker can avoid the problem in the future. Don't be stingy; if it takes fifty words to explain the problem, use fifty words.
Use Chained Exceptions
If you are catching one type and throwing another, chain the cause by passing the original exception to the constructor of the new Exception.
Create Your Own Exceptions
In some cases you may want to return some info beyond a simple message along with the exception. Don't be afraid to write a new exception type that has appropriate parameters.
Using Checked Exceptions
Checked exceptions are out of vogue, largely because of widespread misuse and overuse. Checked exceptions are part of the API of the method - they should be taken as seriously as the return type. They should be clear, meaningful, specific to the problem at hand, and not subject to change for light or transient reasons. See the second link below for a more thorough treatment.
The following article goes into more detail and includes links to further articles on exception handling.
Checked exceptions are out of vogue, but can be used successfully. The following article goes too far, recommending that unchecked exceptions be avoided, but it gives an excellent perspective on proper use of checked exceptions.