Correct generic exception handling (catch(Exception){ … })

A very nice comment tail is growing at the post “Why catch(Exception)/empty is bad” on the CLR team blog. I tend to agree but there are perfectly valid reason’s to do a generic catch but with a correct handler, an empty handler is *always* bad. For example to cleanup some resources that you have allocated or logging some state that could be helpful in reproducing this specific error condition. What my number one rule is regarding generic catches is that they always need to re-throw the catched exception.

void MyMethod(int myCoolNumber){
   try{
      // Doing cool stuff with my cool number!
   }
   catch(Exception ex){
      // We could log about this condition and add the argument value.
      throw;
   }
}

If I see code that has a generic catch but doesn’t re-throw it or that wraps it then the code will be immediately corrected or be marked for refactoring.

Possible corrections:

  • specifying a specific Exception type(s) or
  • adding the throw keyword or
  • removing the wrapped exception after the throw or
  • removing the creation of a new exception without an inner exception
  • Recent Posts
  • Recent Comments
  • Archives
  • Categories
  • Meta