Performance Cost of Wrapping Exceptions

In a previous post I talked about how rethrowing a catch exception can affect the information present in its stacktrace even when using throw;. However throwing a new exception and providing the one that was catch in its inner exception preserves this information.

When faced with an error the more information we have the better so is the cost of newing up an exception significant? Let’s check out with a simplified example:

static void Rethrow(string value)
{
    try { Int32.Parse(value); }
    catch (FormatException)
    { throw; }
}

static void CreateAndThrow(string value)
{
    try { Int32.Parse(value); }
    catch (FormatException e)
    { throw new FormatException("Wrapper", e); }
}

static void Main(string[] args)
{
    const int IterationCount = 50000;

    var sw = new Stopwatch();

    sw.Start();
    for (int i = 0; i < IterationCount; i++)
    {
        try { Rethrow("One"); }
        catch { }
    }
    sw.Stop();
    Console.WriteLine("{0}ms", sw.ElapsedMilliseconds);

    sw.Reset();

    sw.Start();
    for (int i = 0; i < IterationCount; i++)
    {
        try { CreateAndThrow("One"); }
        catch { }
    }
    sw.Stop();
    Console.WriteLine("{0}ms", sw.ElapsedMilliseconds);
}

I run this example several times and the result was always very similar.

Run 1:
4955ms
4986ms

Run 2:
4963ms
5000ms

Run 3:
4977ms
5029ms

As expected the cost of instantiating a new object is diminished by the fact that the application is already in the process of handling an exception. So does this mean that we should start reconsidering the use of throw; and start to use throw new TException(msg, ex);? Maybe.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s