Exception Handling Policy – Catching Exceptions

This is the third installment in my series on sensible exception handling and will cover when and how to catch exceptions.

To quickly summarize, the series looks as follows:

  1. Throwing Exceptions
  2. Using Assertions
  3. Catching Exceptions (this one)
  4. Logging Exceptions

The information in this post is divided into two parts: when to catch, and how to catch.

When to catch

Here are some guidelines on when to catch exceptions and when to let them propagate up through the call stack.

Catch only exceptions you know how to handle, and be specific

If you don’t know ahead of time what the exception is going to be, you don’t know how to handle it, and you should send it up the stack.

Catching top-level exception means trying to deal with the really exceptional case, which by definition you can’t plan for.

Provide a general catch-all

Ensure that all exceptions are caught and reported at some point This is especially important in a multi-threaded environment, where a thread’s death may otherwise go unnoticed.

In languages which also have other error mechanisms, such as PHP, make sure that warnings, errors, fatals etc don’t go unnoticed.

How to catch

When you catch an exception, make sure to do it the right way.

Do not suppress or ignore exceptions

NEVER! EVER! Don’t even while testing. It is not only undisciplined, but you will forget to “deal with it later”.

Always clean up after yourself

Finally is usually recommended to guarantee resource cleanup, however you should yourself guarantee that finally never fails. In general, ensure finally never eats up your original exception.

Declarative exception handling

Handling exceptions is an dynamic concern, the right way to handle an exception can easily change. Therefore, use a flexible framework to manage this.

For example Struts allows user defined ExceptionHandlers to be associated on a local or global scope using configuration instead of code. In other words, responses to exceptions should not only based on type but also on context in where they are called.

Next week, the final episode of the series will be published, so be sure to check back. If you have any comments, please provide them below!