Friday, September 7, 2007

Using Regular Expressions to find Exception blocks which don't use exception chaining.

I have worked on a number of projects where developer have overlooked the importance of exception chaining when handling exceptions and rethrowing them as a different type. This masks the real issue, and makes root cause analysis difficult.

Typically when I start a project, I try to go through all of the code and find all instances of where exception chaining was overlooked.

When working on a project with thousands of source files this can be quite time consuming. Luckily most modern editors support searching through code using regular expressions.

So I wrote a RegEx which will allow me to find all instances where an exception is rethrown, which doesn't use exception chaining. There is one case that this expression returns a false positive, and this is where you rethrow an exception without passing a message to the new one. For Example: throw new Exception(e); But it does help get the job done!

An enhancement I would like to use in the future would be matching groups so that I can easily do find and replace. But, here is what I have for now!

catch[\n\r\s]*\([\n\r\s]*(final[\n\r\s]*)?\S+[\n\r\s]*\S+[\n\r\s]*\)[\n\r\s]*\{[\n\r\s]*throw[\n\r\s]*new[\n\r\s]*\S+\([\n\r\s]*[^,][\n\r\s]*\)

No comments: