ASP.NET Hosting

Hunting down bad try..catch blocks

Way too often developers take the easy solution to use try..catch blocks to silence and ignore exceptions.

There are two things to do when you see this happening:

  1. Explain the developers why it's a bad practice (exceptions are costly and their use should be reserved to exceptional cases), and teach them how to do better (use TryParse, test upfront for known problematic values, etc.)
  2. Hunt down the bad blocks and remove them whenever possible

To spot try..catch blocks with empty catch statements, you can use something simple: Visual Studio's search feature, which allows you to search in files. Of course, you can start by looking for catch{} and catch {} and catch { } and catch {}, but that makes several cases, and doesn't cover the cases where there are line breaks. Luckily, Visual Studio's search support regular expressions, so you can devise one that would match all cases. To get you started, here are some you can use catch.*:b*\n:b*\{:b*\n*:b*\} and catch.*:b*\n:b*\{\} and catch.*:b*\n:b*\{.*\}

I wrote these quickly, so they can be improved. Any expert in regular expression should be able to write a single expression that matches all cases... This could be further improved to include the catch blocks that contain comments such as // ignore exceptions or /* simply ignore this problem */.

7 Comments

  • You could also simply run FxCop ...

  • The easier would be to find the keyword try. As any catch block will have to after a try block find try block (without any need of Regex).

  • Could you explain more precisely what you mean, Vikram?
    Not all uses of "try" mean there is a bad use of "catch". It can be part of try..finally or a good try..catch block.

  • Is there some good article somewhere that explains when to throw and when not to throw?

  • There are some hints about good practices with exception s in the excellent book "Framework Design Guidelines : Conventions, Idioms, and Patterns for Reusable .NET Libraries" and Powerpoint presentation
    "The Art of Building a Reusable Class Library" from Brad Abrams and Krzysztof Cwalina.
    See http://weblogs.asp.net/fmarguerie/archive/2005/09/22/425780.aspx for more information.

  • Here is one which will match Catch blocks that contain only comments:

    catch(\(.*Exception.*\))*:Wh*\{:Wh*(^:Wh*//.*)*:Wh*\}

  • ahh apologies! I forgot that some catch declarations may have spaces inbetween "catch" and the opening "(". The amended regex is "catch:Wh*(\(.*Exception.*\))*:Wh*\{:Wh*(^:Wh*//.*)*:Wh*\}"

Comments have been disabled for this content.