skip to content

In a C# payment-batch processor, a worker thread catches an item's exception and the coordinating thread must rethrow it; how does `ExceptionDispatchInfo` preserve the original stack trace?

level: seniorimportance: nice to knowfreq 22%

answer

  1. throwing a stored exception resets it
  2. capture in the catch, throw later
  3. restore, then append new frames
  4. a marker line in the trace

basics

~20 s

ExceptionDispatchInfo.Capture(ex) in the worker's catch block saves the exception together with its stack trace; calling Throw() on the coordinating thread rethrows the same object with that trace restored and the new frames appended after a marker line.

solid answer

~40 s

A bare `throw;` works only inside the catch block, and `throw storedException;` on another thread treats that line as a new throw point, so the trace shows only the coordinating thread's frames. Wrapping it in a new exception keeps the original as `InnerException` but changes the type callers catch. `ExceptionDispatchInfo` in `System.Runtime.ExceptionServices` solves this: `Capture(ex)` in the worker's catch block records the exception's dispatch state, and `Throw()` restores it before throwing the same object, so the trace lists the worker's original frames, then `--- End of stack trace from previous location ---`, then the frames where it was rethrown. Type, message and `Data` are unchanged. `Throw()` is marked `[DoesNotReturn]`, but the compiler's reachability analysis ignores that, so a value-returning method still needs a `return` or `throw` after the call (CS0161 otherwise).

code

csharp · 30 lines
csharp
#:property PublishAot=false
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;

ExceptionDispatchInfo? failure = null;

var worker = new Thread(() =>
{
    try { Gateway.Charge("INV-7"); }
    catch (Exception ex) { failure = ExceptionDispatchInfo.Capture(ex); }
});
worker.Start();
worker.Join();

try
{
    failure?.Throw();
}
catch (InvalidOperationException ex)
{
    foreach (var line in ex.StackTrace!.Split(Environment.NewLine))
        Console.WriteLine(line.Split(" in ")[0]);
}

static class Gateway
{
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static void Charge(string id) =>
        throw new InvalidOperationException($"{id} declined");
}

go deeper

for a junior

Recall that rethrowing a stored exception with throw ex resets its trace, and that ExceptionDispatchInfo exists to rethrow later without that loss.

for a middle

Explain Capture in the catch block and Throw at the rethrow site, and how to read the End of stack trace from previous location marker.

for a senior

Compare throw ex, wrapping and ExceptionDispatchInfo for a cross-thread hand-off, and mention CS0161 after Throw() and that await relies on the same mechanism.

for a principal

Prefer tasks for new designs; keep ExceptionDispatchInfo for hand-offs you own and require that rethrown failures keep their original type and trace.

## The problem: an exception that crosses threads A payment-batch processor often hands items to **worker threads** and waits for them on a **coordinating thread**. When a worker's charge call fails, the worker catches the exception (an uncaught exception on a thread would end the process) and stores it. The coordinator must then surface that failure to its own caller, ideally as the **same exception, with the same type and the same stack trace**, so that the caller's catch clauses and the operator's logs work as if the call had happened on one thread. A bare `throw;` cannot do this: it is legal only lexically inside a `catch` block (CS0156 elsewhere), and the coordinator is not in one. ## Three ways to rethrow a stored exception | Approach | Type seen by callers | Stack trace | |---|---|---| | `throw failure;` on the coordinator | original | reset: only the coordinator's frames from the throw onward | | `throw new InvalidOperationException("Item failed", failure);` | the new wrapper type | original kept inside `InnerException` | | `ExceptionDispatchInfo.Capture(failure).Throw()` | original | original frames restored, coordinator frames appended | Run on .NET 10, the first approach printed a single frame, `at Program.<Main>$(String[] args)`: the worker's frames were gone. Wrapping is a legitimate design when the coordinator wants its own exception type, but it changes what callers must catch, which is a decision about your API rather than a rethrow. ## Capture and Throw `ExceptionDispatchInfo` (namespace `System.Runtime.ExceptionServices`) separates an exception object from the details of how it was dispatched. The reference source describes it as useful "for frameworks that wish to propagate exceptions ... across threads". Its surface is small: - `static ExceptionDispatchInfo Capture(Exception source)`: records the exception's current dispatch state, including its stack trace. Call it **inside the catch block**, where the trace is complete. - `void Throw()`: restores that state onto the exception object and throws it. The method is marked `[StackTraceHidden]`, so it does not appear in the trace itself. - `static void Throw(Exception source)`: shorthand for `Capture(source).Throw()`. - `Exception SourceException`: the captured object, for logging or inspection without throwing. In the code example the worker's catch block captures, the main thread joins and calls `failure?.Throw()`, and the printed trace is: 1. `at Gateway.Charge(String id)`: the original throw site on the worker thread. 2. `at Program.<>c__DisplayClass0_0.<<Main>$>b__0()`: the worker's lambda. 3. `--- End of stack trace from previous location ---`: the boundary between captured and new frames. 4. `at Program.<Main>$(String[] args)`: where the coordinator rethrew. That marker line is different from `--- End of inner exception stack trace ---`, which separates an outer exception from its `InnerException` when `ToString()` prints both. ## The reachability trap `Throw()` is annotated `[DoesNotReturn]`, which nullable analysis honours. The compiler's **definite-assignment and reachability analysis does not**: a method declared to return `int` whose body ends with `edi.Throw();` fails with **CS0161**, "not all code paths return a value". Add a `return` after the call, or throw something explicit such as `System.Diagnostics.UnreachableException`, so the method compiles and the intent stays clear. ## Where you meet this mechanism - **Your own thread hand-offs**: a `Thread`, a callback on a native or I/O thread, a producer-consumer pipeline that reports a failed item back to the coordinator. - **Inside the runtime**: awaiting a faulted task rethrows its exception with the original trace, and the trace shows the same marker line; how tasks and `await` surface exceptions is covered with asynchronous code. - **Code-analysis guidance**: the docs for CA2200 point to `ExceptionDispatchInfo.Capture` and `Throw` for rethrowing "from somewhere other than the handler". ## Practical rules - Capture in the catch block, once, and store the `ExceptionDispatchInfo` rather than the bare exception. - Log through `SourceException` before rethrowing if the coordinator wants its own record; reading it does not change the captured state. - Rethrow it once on the coordinating path; for several failed items, decide whether to surface the first, or to collect them and report them together. - Prefer higher-level primitives (tasks and `await`) when you control the design; reach for `ExceptionDispatchInfo` when you own the thread hand-off yourself.

  • Why not just store the exception and run `throw failure;` on the coordinating thread?
    Throwing a stored exception object treats that line as a new throw point, so the runtime resets its stack trace. On .NET 10 the result showed only the coordinator's own frame; the worker's frames, including the failing method, were gone. `ExceptionDispatchInfo.Throw()` restores the captured trace before throwing.
  • A method returning `decimal` ends with `edi.Throw();`. Why doesn't it compile, and what is the fix?
    The compiler's reachability analysis does not use the `[DoesNotReturn]` attribute on `Throw()`, so it reports CS0161, not all code paths return a value. Add a `return` after the call or throw something explicit such as `UnreachableException`; neither runs, because `Throw()` always throws.

  • throwing the stored exception object keeps its original trace
  • a bare throw; works anywhere as long as an exception was caught earlier
  • wrapping in a new exception is equivalent, since nothing is lost
  • Capture can be called anywhere later, not only in the catch block
  • the compiler knows Throw() never returns, so no return is needed after it