Possible Duplicate:
difference between throw and throw new Exception()
What would be the point of just having
catch (Exception) { throw; }
What does this do?
A throw statement can be used in a catch block to re-throw the exception that is caught by the catch statement. The following example extracts source information from an IOException exception, and then throws the exception to the parent method.
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
Exceptions are used to indicate that an error has occurred while running the program. Exception objects that describe an error are created and then thrown with the throw keyword. The runtime then searches for the most compatible exception handler.
The following example uses the throw statement to throw an IndexOutOfRangeException if the argument passed to a method named GetNumber does not correspond to a valid index of an internal array. Method callers then use a try-catch or try-catch-finally block to handle the thrown exception.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With