Daily Archives: December 14, 2006

Why you shouldn’t catch System.Exception

There are probably many reasons, but my favorite is that, if you are resorting to catching anything at all, you probably don’t understand the code well.

For example, in complicated parsing of text, it is often easier to just put a huge try {…} catch (Exception ex) {…} around the entire thing, rather than take the time necessary to understand how your code works, and where exactly things could go wrong.

It is much better to go through the code line-by-line and prove to yourself that that there are only a few places of possible unknown exception behavior. Obviously, exceptions are meant to catch things you can’t reliably predict, but in most code, there are large areas of things like string manipulation, arithmetic, or other simple procedures, that will not throw an exception. It makes sense to delineate these areas, and surround only the trouble spots with try-catch.

For example, look at this fragment:

string strDelimiters = ":, ;"; 
try 
{ 
    string[] tempStrings = message.Split(strDelimiters.ToCharArray()); 
    string[] subStrings = new string[tempStrings.Length]; 
    int numSubStrings = 0; 
    //remove empty substrings 
    for (int i=0;i<tempStrings.Length;i++) 
    { 
        if (tempStrings[i] != null && tempStrings[i].Length > 0) 
        { 
            subStrings[numSubStrings] = tempStrings[i]; 
            numSubStrings++; 
        } 
    } 
...

 There is no reason to surround this with a try {} catch{} block. Doing so lets you off the hook of digging into this and realizing how bad it is, especially with .Net 2.0. 🙂