Six rules for effective exception handling

Exception handling in .Net (and other languages) is very powerful – and I’ve often seen it misused. Here are my six rules for exception handling.

  1. Always have a global exception handler to catch, report, and re-throw unhandled exceptions in your code.
  2. Always be sure to include the stack trace in your exception report. The easy way to do this is to use Exception.ToString().
  3. If you need to catch an exception, always use the most specific exception for the code you’re writing. Don’t catch Exception when you are expecting a FileIOException. Leave the general exception catching for the global exception handler (#1).
  4. Never ever catch an exception and do nothing (i.e. an empty catch or finally block). If you can find a convincing reason to do this, I would love to disprove it.
  5. If catching and re-throwing an exception, always specify throw, not throw (ex). If you do the latter, you’ll the stack trace.
  6. Wrapping all the code in a function inside a try/catch block is not effective exception handling. Instead, wrap code in try/catch blocks where the exception can be anticipated ahead of time, and dealt with accordingly.

Fortunately, these rules apply to .Net code, SQL code, Java code, and any other language that supports this style of exception handling.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.