What does "throw;" by itself do?

C#.NetException

C# Problem Overview


> Possible Duplicate:
> difference between throw and throw new Exception()

What would be the point of just having

catch (Exception)
{
    throw;
}

What does this do?

C# Solutions


Solution 1 - C#

By itself, the throw keyword simply re-raises the exception caught by the catch statement above. This is handy if you want to do some rudimentary exception handling (perhaps a compensating action like rolling back a transaction) and then rethrow the exception to the calling method.

This method has one significant advantage over catching the exception in a variable and throwing that instance: It preserves the original call stack. If you catch (Exception ex) and then throw ex, your call stack will only start at that throw statement and you lose the method/line of the original error.

Solution 2 - C#

Sometimes you might want to do something like this:

try
{
    // do some stuff that could cause SomeCustomException to happen, as 
    // well as other exceptions
}
catch (SomeCustomException)
{
    // this is here so we don't double wrap the exception, since
    // we know the exception is already SomeCustomException
    throw;
}
catch (Exception e)
{
    // we got some other exception, but we want all exceptions
    // thrown from this method to be SomeCustomException, so we wrap
    // it
    throw new SomeCustomException("An error occurred saving the widget", e);
}

Solution 3 - C#

It rethrows the exact same error, you gain nothing by this.
Sometimes you can use the catch method to do some logging or something without interupting your exception like this:

catch (Exception) {
  myLogger.Log(LogLevels.Exception, "oh noes!")
  throw; 
}

I initially mistakingly thought this would unwind your stack, but this would only be if you would do the following:

catch (Exception err) {
  throw err; 
}

Solution 4 - C#

Only reason I can think of is if you want to put a breakpoint there during debugging.
It's also the default code being generated by some tools I think.

Solution 5 - C#

Simply rethrow the current exception, and that exception will keep its "source" and the stack trace.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCJ7View Question on Stackoverflow
Solution 1 - C#Matt HamiltonView Answer on Stackoverflow
Solution 2 - C#dcpView Answer on Stackoverflow
Solution 3 - C#Boris CallensView Answer on Stackoverflow
Solution 4 - C#Hans OlssonView Answer on Stackoverflow
Solution 5 - C#RajeshView Answer on Stackoverflow