Tips & Tricks: Catch and throw on different threads

The .Net 4.5 has a new addition that allows one to re-throw an exception on a different thread than the one on which the exception has been caught. The big advantage is not the fact that we are able to re-throw the exception (this was possible in previous versions of .Net) but the fact that the stack trace of the exception is preserved.

Currently there are 3 different ways of re-throwing an exception:

1. Using the throw keyword with no identifier (this one preserves the original stack trace):

try
{
    throw null;
}
catch
{
    throw;
}

2. Using the throw keyword with the original exception (this one deletes the original stack trace):

try
{
    throw null;
}
catch (Exception ex)
{
    throw ex;
}

3. Using the throw keyword with a new exception and wrapping the original exception as InnerException:

try
{
    throw null;
}
catch (Exception ex)
{
    throw new Exception("Custom", ex);
}

NOTE: It is not recommended to use Exception class directly (I have used it only for the brevity of the examples).

In .Net 4.5 there is a new possibility of re-throwing  exceptions and preserving the original stack trace: to accomplish all this one can use ExceptionDispatchInfo class from System.Runtime.ExceptionServices namespace.

As stated on MSDN, “the ExceptionDispatchInfo object stores the stack trace information and Watson information that the exception contains at the point where it is captured. The exception can be thrown at another time and possibly on another thread by calling the ExceptionDispatchInfo.Throw method”:

using System;
using System.Runtime.ExceptionServices;

class Program
{
    static void Main()
    {
        ExceptionDispatchInfo edi = null;

        try
        {
            throw null;
        }
        catch (Exception ex)
        {
            edi = ExceptionDispatchInfo.Capture(ex);
        }

        if (edi != null)
        {
            edi.Throw();
        }
    }
}
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