HiveBrain v1.2.0
Get Started
← Back to all entries
debugcsharpCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
therethrowproperexceptionwaywhat

Problem

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?

Solution

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
}

Code Snippets

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
}

Context

Stack Overflow Q#178456, score: 928

Revisions (0)

No revisions yet.