What does "throw;" by itself do? [duplicate]
Solution 1:
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:
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:
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.