Friday, December 18, 2009

Regular Expression to fix exception handling

I was doing a code review and saw a common mistake throughout the code:

try
{
}
catch(Exception ex)
{
throw ex;
}

this is incorrect. When you rethrow an exception like this, you reset the call stack and hose the good error information.

The correct method is:

try
{
}
catch(Exception ex)
{
throw;
}


I came up with a quick regular expression you can use in visual studio to fix these. Press control-shift-f and check the box "use " where it says "regular expressions"

In the "Find What" section enter in:


{catch[:Wh]*\{[:Wh]*throw}{ ex}{;[:Wh]*\}}

In the "Replace with" enter:
\1\3

What does this do? In visual studio regular expressions the groupings are done by {} so the first place I have {} is \1, the second place is \2, etc

so this expression: {catch[:Wh]*\{[:Wh]*throw}{ ex}{;[:Wh]*\}}
breaks down to:
{catch[:Wh]*\{[:Wh]*throw} =\1
{ ex} =\2
{;[:Wh]*\}} =\3
so by replacing with \1\3 I simply exclude the " ex"


Click "replace" or "replace all" - by clicking replace you can preview one at a time.

1 comment:

Note: Only a member of this blog may post a comment.