Throwing an exception from a different method while preserving its information

suggest change

Sometimes you catch an exception and need to throw it again from another method, while keeping the original stack trace. ExceptionDispatchInfo does that. It was added in .NET Framework 4.5.

using System.Runtime.ExceptionServices;

void Main()
{
    ExceptionDispatchInfo capturedException = null;
    try
    {
        throw new Exception();
    }
    catch (Exception ex)
    {
        capturedException = ExceptionDispatchInfo.Capture(ex);
    }
    
    Foo(capturedException);
}

void Foo(ExceptionDispatchInfo exceptionDispatchInfo)
{
    // Do stuff

    if (exceptionDispatchInfo != null)
    {
        // Exception stack trace will show it was thrown from Main() and not from Foo()
        exceptionDispatchInfo.Throw();
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents