Skip to main content

Execute Around Exception

I have a lot of UI controller code that looks like this:

try
{
// Do something that might throw is is probably a single line of code
}
catch (Exception e)
{
// Notify the user of the problem.
}

This is 8 lines of code for a single line operation. The common code that notifies the user of the error, commonly just a message box, can easily be refactored into a single method. The problem is the try/catch block. So I started wondering if I could reduce it somehow. I would be so much nicer if I could write:

ExecuteSafely(delegate
{
// Do something that might throw is is probably a single line of code
});

where ExecuteSafely takes care of the boiler plate code. I started playing around with Execute Around Method ideas and came up with this:

public class ExecuteAroundException
{
private readonly Action<Exception> exceptionHandler;

public ExecuteAroundException()
: this(delegate { })
{
}

public ExecuteAroundException(Action<Exception> exceptionHandler)
{
this.exceptionHandler = exceptionHandler;
}

public void ExecuteSafely(Action action)
{
try
{
action();
}
catch (Exception e)
{
exceptionHandler(e);
}
}
}

The default exceptionHandler does nothing. It just swallows the exception. The chances of you wanting to use it are therefore slim. However you can provide a delegate that handles the exception:

ExecuteAroundException x = new ExecuteAroundException(delegate(Exception e)
{
// Notify the user of the problem.
});

And then you can use it like this:
       
x.ExecuteSafely(delegate
{
// Do something that might throw is is probably a single line of code
});

The only two scenarios where this is worth while is when the ExecuteAroundException instance is created once at class scope or created in a factory method. Otherwise you end up with almost as much code.

Comments