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

  1. Like the idea of ExecuteSafely, although not convinced about the ExecuteAroundException, although that does allow it to be passed around as a sort of policy object.

    I've had a play around with this, and for my purposes come up with something like the stuff below:


    // Provides primatves for further development
    public static class XH
    {

    // Execute Safely

    public static void ExecuteSafely< TException >(
    Action action,
    Action< TException > eh )
    where TException : Exception
    {
    try
    {
    action(null);
    }
    catch( TException ex )
    {
    eh( ex );
    }
    }

    public static void ExecuteSafely(
    Action action )
    {
    Action< Exception > eh = NoOpExceptionHandler;

    ExecuteSafely( action, eh );
    }


    // potentially could have versions taking multiple TException types for different actions, but becomes unwieldy very quickly.
    // e.g. to perform logging on all exceptions to a DB, but do something more clever on a DBGoneAwayException.
    public static TReturnType ExecuteSafely< TReturnType, TException >(
    Func action,
    Action< TException > eh )
    where TException : Exception
    {
    try
    {
    return action(null);
    }
    catch( TException ex )
    {
    eh( ex );

    return default(TReturnType);
    }
    }


    public static TReturnType ExecuteSafely(
    Func action )
    {
    Action< Exception > eh = NoOpExceptionHandler;

    return ExecuteSafely( action, eh );
    }


    // Execute

    public static void Execute< TException >(
    Action action,
    Func< TException > eh )
    where TException : Exception
    {
    try
    {
    action(null);
    }
    catch( TException ex )
    {
    if( eh( ex ) )
    {
    throw;
    }
    }
    }

    public static void Execute(
    Action action )
    {
    Func< Exception > eh = delegate( Exception ex)
    {
    NoOpExceptionHandler( ex );
    return false;
    }

    Execute( action, eh );
    }


    // potentially could have versions taking multiple TException types for different actions, but becomes unwieldy very quickly.
    // e.g. to perform logging on all exceptions to a DB, but do something more clever on a DBGoneAwayException.
    public static TReturnType ExecuteSafely< TReturnType, TException >(
    Func action,
    Func< TException > eh )
    where TException : Exception
    {
    try
    {
    return action(null);
    }
    catch( TException ex )
    {
    if( eh( ex ) )
    {
    throw;
    }
    }
    }


    public static TReturnType ExecuteSafely(
    Func action )
    {
    Func< Exception > eh = delegate( Exception ex)
    {
    NoOpExceptionHandler( ex );
    return false;
    }

    return Execute( action, eh );
    }


    // Common Exception handling Policies
    public static void NoOpExceptionHandler( Exception ex )
    {
    }
    }


    Where I've used this I've provided local ExecuteSafely in the class that knows how to handle the exception:

    class AboutBox : Form
    {
    private btnExplode_Click( ... )
    {
    ExecuteSafely( delegate {
    throw new Exception();
    });
    }


    public static void ExecuteSafely(
    Action action )
    {
    Action< Exception > eh = delegate( Exception ex ) {
    MessageBox.Show( this, "It's broken" );
    };

    XH.ExecuteSafely( action, eh );
    }

    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Write Your Own Load Balancer: A worked Example

I was out walking with a techie friend of mine I’d not seen for a while and he asked me if I’d written anything recently. I hadn’t, other than an article on data sharing a few months before and I realised I was missing it. Well, not the writing itself, but the end result. In the last few weeks, another friend of mine, John Cricket , has been setting weekly code challenges via linkedin and his new website, https://codingchallenges.fyi/ . They were all quite interesting, but one in particular on writing load balancers appealed, so I thought I’d kill two birds with one stone and write up a worked example. You’ll find my worked example below. The challenge itself is italics and voice is that of John Crickets. The Coding Challenge https://codingchallenges.fyi/challenges/challenge-load-balancer/ Write Your Own Load Balancer This challenge is to build your own application layer load balancer. A load balancer sits in front of a group of servers and routes client requests across all of the serv

Bloodstock 2009

This year was one of the best Bloodstock s ever, which surprised me as the line up didn't look too strong. I haven't come away with a list of bands I want to buy all the albums of, but I did enjoy a lot of the performances. Insomnium[6] sound a lot like Swallow the Sun and Paradise Lost. They put on a very good show. I find a lot of old thrash bands quite boring, but Sodom[5] were quite good. They could have done with a second guitarist and the bass broke in the first song and it seemed to take ages to get it fixed. Saxon[8] gave us some some classic traditional heavy metal. Solid, as expected. The best bit was, following the guitarist standing on a monitor, Biff Bifford ripped off the sign saying "DO NOT STAND" and showed it to the audience. Once their sound was sorted, Arch Enemy[10] stole the show. They turned out not only to be the best band of the day, but of the festival, but then that's what you'd expect from Arch Enemy. Carcass[4] were very disappoin

Catalina-Ant for Tomcat 7

I recently upgraded from Tomcat 6 to Tomcat 7 and all of my Ant deployment scripts stopped working. I eventually worked out why and made the necessary changes, but there doesn’t seem to be a complete description of how to use Catalina-Ant for Tomcat 7 on the web so I thought I'd write one. To start with, make sure Tomcat manager is configured for use by Catalina-Ant. Make sure that manager-script is included in the roles for one of the users in TOMCAT_HOME/conf/tomcat-users.xml . For example: <tomcat-users> <user name="admin" password="s3cr£t" roles="manager-gui, manager-script "/> </tomcat-users> Catalina-Ant for Tomcat 6 was encapsulated within a single JAR file. Catalina-Ant for Tomcat 7 requires four JAR files. One from TOMCAT_HOME/bin : tomcat-juli.jar and three from TOMCAT_HOME/lib: catalina-ant.jar tomcat-coyote.jar tomcat-util.jar There are at least three ways of making the JARs available to Ant: Copy the JARs into th