0

Given the following statements:

try
{
    ... some code ...
}
catch
{
    ... some cleanup code ...
    throw;
}

and

try
{
    ... some code ...
}
catch (Exception ex)
{
    ... some cleanup code ...
    throw ex;
}

Do these operate the same, or will the first one cause a new exception to be thrown?

Scottie
  • 11,050
  • 19
  • 68
  • 109

4 Answers4

4

They are not the same. In the second version, stack information is lost.

More elaborate explanation here: http://winterdom.com/2002/09/rethrowingexceptionsinc

From that site:

In the [second piece of] code [..], you're not rethrowing ex, just merely beginning a new exception flow using the same exception object instance.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
3

The former throws the original exception; the latter throws a new exception. They act generally the same, except that the former keeps the original stack trace, while the latter only has the stack trace starting from where the exception was re-thrown.

neminem
  • 2,658
  • 5
  • 27
  • 36
1

There are two diffrences

First you are correct the 2nd one causes a new exception to be thrown with a new stack trace. This will cause you to loose valuable debugging information and should never be done. The correct way to do the 2nd example would be

try
{
    ... some code ...
}
catch (Exception) //You can include the "ex" if you need it in your cleanup code
{
    ... some cleanup code ...
    throw; //Don't use the "ex" here
}

The 2nd difference is there are a very vary small number of exceptions that the first example will catch that the 2nd example will not. Mainly these exceptions are ones thrown from non CLR complient code. There is no way to throw a non Exception derived exception from C# code.

One thing if you want to add additional information to the exception before you bubble it up you can throw a new exception and put the old exception as the InnerException

try
{
    ... some code ...
}
catch (Exception ex)
{
    ... some cleanup code ...
    throw new MyCustomException("Some useful information", ex);
}
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
  • Actually, the CLR itself will not throw non-`Exception`s. They can only be thrown by external non-CLS-compliant code in other languages. – SLaks Oct 01 '13 at 17:35
  • @SLaks I knew it was something special, I was going to research it and correct if need be after I posted. I have corrected it. – Scott Chamberlain Oct 01 '13 at 17:36
0

No. From my experience, though not much, I've tried both solutions and the second seems to catch only the specified exception, though the first would catch ANY exception. Hope this helps.

Articulous
  • 191
  • 1
  • 4
  • 16