Throwing an exception from a different method while preserving its information
suggest changeSometimes 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();
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents