Exception dispatch info

Imagine you have a simple code as shown below:

class Program
{
static void Main()
{
try
{
SimpleErrorCheck();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}

public static void SimpleErrorCheck()
{
try
{
int b = 1;

int result = (b / (b - 1));

Console.WriteLine("Result is {0}", result);
}
catch (Exception ex)
{
// log

throw;
}
}
}

A call is made to SimpleErrorCheck() method where we do some calculations that results in a divide by zero exception.

Using throw ex overwrites the stack trace while using throw keeps it intact so that you can go back and see where exactly the error happened. You can also examine generated IL and see rethrow is used if we do throw ex.

throw is only available inside catch block. If there is some stuff like code related to rollback or anything else that you would like to do outside of catch block and then throw the error, you will have to rethrow which will overwrite the stack trace.

In .Net 4.5 ErrorDispatchInfo class is introduced to solve this problem.
 
Let’s change our code to use ErrorDispatchInfo class:
 
class Program
{
static void Main()
{
try
{
SimpleErrorCheck();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}

public static void SimpleErrorCheck()
{
ExceptionDispatchInfo exInfo = null;

try
{
int b = 1;

int result = (b / (b - 1));

Console.WriteLine("Result is {0}", result);
}
catch (Exception ex)
{
exInfo = ExceptionDispatchInfo.Capture(ex);
}

// do some operation
if (exInfo != null)
{
exInfo.Throw();
}
}
}

Let’s examine the stack trace that we got in console:

image

Stack trace of original exception is preserved and we can get exact line of code.

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