Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "throw;" by itself do? [duplicate]

Tags:

c#

.net

exception

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

What would be the point of just having

catch (Exception) {     throw; } 

What does this do?

like image 765
CJ7 Avatar asked Apr 28 '10 10:04

CJ7


People also ask

What does throw do in try-catch?

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.

What does a throw do?

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.

What does throw do in exception in C#?

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.

How does throw work in C#?

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.


1 Answers

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.

like image 180
Matt Hamilton Avatar answered Nov 15 '22 13:11

Matt Hamilton