tags:

views:

366

answers:

5

What would be the point of just having:

catch (Exception)
{
    throw;
}

What does this do?

+1  A: 

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; 
}
borisCallens
Are you sure you have the extra stack unwind, since using "throw" alone will just rethrow the original exception with the exact stacktrace as the original... right?!
veggerby
@boris: are you saying some code will be executed twice?
Craig Johnston
@Veggerby: You are right, I was confusing with the case where you say catch(Exception ex){throw ex}. In the case of the question's code, nothing happens really.@Craig: No nothing gets executed twice
borisCallens
+3  A: 

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.

ho1
+36  A: 

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.

Matt Hamilton
As I understand the question, the whole contents of the `catch` block is `throw;`, so no additional exception handling. I may be wrong, though.
Gorpik
What is your response to boris' point?
Craig Johnston
Boris is right in that the example provided doesn't really do anything, but I don't believe there's any change to the call stack.
Matt Hamilton
+1 for explaining the original call stack preservation, very important!
Sandor Drieënhuizen
borisCallens
+4  A: 

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
    throw;
}
catch (Exception e)
{
    throw new SomeCustomException("An error occurred saving the widget", e);
}
dcp
+1  A: 

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

Rajesh