Download the code here.

While working on a recent gig, one of the requirements for the code I was developing was to have extensive logging, on both new code being developed & on the existing codebase.   Due to the mix of new & old code, a lot of files ended up being cluttered with try…catch blocks:

try
{
    /* Relatively Simple Operation(s) */
}
catch (Exception ex)
{
    /* Logging Routines... */

    /* UI Error Display... */
}

While there’s nothing wrong with multiple try/catch blocks, in this particular application they were causing quite a bit of code duplication in the logging & UI display code.  To reduce the code duplication and make the code a bit more readable, I created an ExceptionCatcher class to wrap up the duplicated code and reduce most of the previous multiple line try/catch blocks to just a few lines ( typically turning into 1-liners). 

The ExceptionCatcher is fairly simple, as it is essentially just a single method call that takes an Action, which it executes in the context of its own try/catch block.

A typical line of code looks something like this:

ExceptionCatcher.Try<BusinessException>(() => { saveBusinessObject(); });

In this call, the ExceptionCatcher will catch BusinessExceptions and then perform any logic in its own Catch block.  The Try method does return an ExceptionCatcherResult to let the calling code know about any exception that occurred, however there typically wasn’t any necessity to do so.  There’s also an overload on the Try method to rethrow the Exception, to handle cases where you need to perform some action and then let the exception continue to bubble up through the code.

I’ve included a sample project that demo’s a simpler version of the ExceptionCatcher.  The core functionality is housed in the ExceptionCatcher class, and contains a few overloads to handle the scenarios above. 

You can download the code here.

Feel free to send any questions or comments to me using the comments link on this post!

- Colin