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.
- Always have a global exception handler to catch, report, and re-throw unhandled exceptions in your code.
- Always be sure to include the stack trace in your exception report. The easy way to do this is to use
Exception.ToString()
. - 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 aFileIOException
. Leave the general exception catching for the global exception handler (#1). - 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.
- If catching and re-throwing an exception, always specify
throw
, notthrow (ex)
. If you do the latter, you’ll the stack trace. - 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.