Thursday, November 20, 2008

Exceptions

One of my pet peeves is a developer not implementing exception handling in a useful manner. Exception handling needs to be an important part of design and not just wrapping all your code in a try/catch block. This does nothing for me:

catch (Exception ex)
{
    [Do something]
}


even worse is this:

catch (Exception ex)
{
    [Do something]
    throw ex;
}


All this does is give away the full stack trace for any exception handling further up the chain.

A better pattern/design/practice for handling exceptions would be to actually handle any exceptions you're catching. That means catching specific exceptions like InvalidOperationException, ArgumentException , or even better, a custom, meaningful exception specific to the task instead of the base Exception.

Speaking of custom, if you're going to define your own exceptions, be sure to provide grammatically correct messages that will be meaningful to someone down the road. Also include the three common constructors that are implemented by all the system exceptions (No parameters, single string parameter, and string parameter and inner exception parameter).

When throwing exceptions, use care to choose the correct type instead of just throwing ApplicationException. Consider returning null for cases of extremely common errors instead of throwing an exception. And most importantly, don't use exceptions as part of normal program flow. Remember try/catch is analogous to a goto statement so don't abuse it.

Resources:
http://msdn.microsoft.com/en-us/library/seyhszts.aspx

No comments: