Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to rethrow an exception in C#? [duplicate]

Tags:

c#

.net

exception

Is it better to do this:

try {     ... } catch (Exception ex) {     ...     throw; } 

Or this:

try {     ... } catch (Exception ex) {     ...     throw ex; } 

Do they do the same thing? Is one better than the other?

like image 710
Patrick Desjardins Avatar asked Oct 07 '08 13:10

Patrick Desjardins


People also ask

How do you Rethrow an exception?

If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.

What does Rethrow the exception mean?

Re-throwing an exception means calling the throw statement without an exception object, inside a catch block. It can only be used inside a catch block.

Should you Rethrow exceptions?

THE MAIN REASON of re-throwing exceptions is to leave Call Stack untouched, so you can get more complete picture of what happens and calls sequence.

How can we Rethrow an exception in C#?

An exception caught by one catch can be rethrown so that it can be caught by an outer catch. To rethrow an exception, you simply specify throw, without specifying an expression.


1 Answers

You should always use the following syntax to rethrow an exception. Else you'll stomp the stack trace:

throw; 

If you print the trace resulting from throw ex, you'll see that it ends on that statement and not at the real source of the exception.

Basically, it should be deemed a criminal offense to use throw ex.


If there is a need to rethrow an exception that comes from somewhere else (AggregateException, TargetInvocationException) or perhaps another thread, you also shouldn't rethrow it directly. Rather there is the ExceptionDispatchInfo that preserves all the necessary information.

try {     methodInfo.Invoke(...); } catch (System.Reflection.TargetInvocationException e) {     System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw();     throw; // just to inform the compiler that the flow never leaves the block } 
like image 63
Torbjörn Gyllebring Avatar answered Sep 18 '22 23:09

Torbjörn Gyllebring