Centralized exception handling

Exception handling is a very useful mechanism to improve a program’s robustness. In case an unexpected exception occurs, developers commonly write a code block as follows:

try
{
  // Do something
}
catch (Exception ex)
{
  // Log the exception
  // Notify the user about the exception
}

That code block is very often duplicated everywhere in the project. It is obviously not a good coding practice. Instead of duplicating, we should extract and promote it as a subroutine. That way, we can gain the following advantages:

  1. More maintainable; if the exception handling is kept in a single place, it is easy to apply future modifications.
  2. More productive; less amount of code to write (or copy) means less coding time and less possibility of error.
  3. Separation of concern; each routine will be much clearer since it is not polluted with exception handling, logging, and notification code blocks.

Centralized exception handling implementation

If you already have or willing to use Microsoft Enterprise Library, there is already the Exception Handling Application Block for you to use.

But you can easily implement your own. The basic idea is create a method with your exception handling block. This method must be able to accept and execute a code block. To achieve this we can use delegate. In .NET Framework 3.5, it is even simpler with the Action delegate.

The code executes inside the try block, while in the catch block, all necessary treatments (logging and notification) can be added.

The following is a sample skeleton of the implementation built as a method called TryExecute:

void TryExecute(Action code)
{
  try
  {
    code(); // Execute the passed code
  }
  catch (Exception ex)
  {
    // Log the exception
    // Notify the user
    // Add more things as required
  }
}

Then, in your client code, you can just call it as follows:

void SomeMethod()
{
  // Send the code inside the block to the TryExecute() method.
  TryExecute(() =>
  {
    // Do something
  });
}

Easy, right?

  • Ganesh

    This doesn’t seem to work. The client code as shown above gives compile errors. Does not recognize the way the TryExecute block is written. Are you missing something?

    • http://www.denniland.com/ Denni Gautama

      Hi Ganesh,

      The code format was messed up. I’ve corrected it. Please try again.