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

Patrick Desjardins picture Patrick Desjardins · Oct 7, 2008 · Viewed 194.4k times · Source

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?

Answer

Torbjörn Gyllebring picture Torbjörn Gyllebring · Oct 7, 2008

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".