0 day streak
csharp / expert
Snippet

Preserving Exception Source with ExceptionDispatchInfo

In high-level C# error handling, using 'throw ex' resets the stack trace to the current line. ExceptionDispatchInfo allows you to capture an exception and re-throw it while preserving the original source and stack trace, which is critical for debugging complex async or layered applications.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System.Runtime.ExceptionServices;
try
{
// Complex operation that might fail
ExecuteProcess();
}
catch (Exception ex)
{
// Capture exception state to avoid losing stack trace on re-throw
var dispatchInfo = ExceptionDispatchInfo.Capture(ex);
LogFailure(ex);
// Rethrows without modifying the 'StackTrace' property
dispatchInfo.Throw();
}
Breakdown
1
ExceptionDispatchInfo.Capture(ex)
Captures the exception object and its current call stack state into a container.
2
dispatchInfo.Throw()
Rethrows the captured exception while maintaining the original stack information as if it was never caught.