What is the proper way to re-throw an exception in C#?


Question

I have a question for you that stems from my partner doing things a different way than I do.

Is it better to do this :

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

or this:

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

Do they do the same thing? Is one better than the other?

1
427
11/21/2013 5:48:35 AM

Accepted Answer

You should always use following syntax to rethrow an exception, else you'll stomp the stack trace:

throw;

If you print the trace resulting from "throw ex", you'll see that it ends on that statement and not at the real source of the exception.

Basically, it should be deemed a criminal offense to use "throw ex".

749
9/17/2014 11:44:31 PM

My preferences is to use

try 
{
}
catch (Exception ex)
{
     ...
     throw new Exception ("Put more context here", ex)
}

This preserves the original error, but allows you to put more context, such as an object ID, a connection string, stuff like that. Often my exception reporting tool will have 5 chained exceptions to report, each reporting more detail.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon