skip to content

Throwing and Catching

throw; keeps the stack trace while throw ex resets it, catch order matters, and when filters run before unwinding. Interviewers ask what finally guarantees.

on this pageshow

explore

questions

6

In C#, what is the difference between `throw;` and `throw ex;` inside a catch block, and which one should you use to rethrow?

level: juniorimportance: must knowfreq 78%

answer

  1. what the stack trace remembers
  2. same object, different throw point
  3. an analyzer warns on one form
  4. bare form only inside catch

basics

~20 s

Both rethrow the same exception object, but throw ex; restarts its stack trace at the rethrow line and hides where the failure really happened, while a bare throw; keeps the original trace. Use throw; to rethrow from a catch block.

solid answer

~40 s

Inside a `catch` block, `throw;` rethrows the exception being handled and leaves its `StackTrace` intact, so the trace still starts in the method that originally threw. `throw ex;` throws the same object again as if this line were a brand-new throw point: the runtime resets the trace, and every frame between the original throw and the catch is lost. The message, type and `InnerException` do not change, only the trace. The .NET analyzers flag `throw ex;` with CA2200, "Rethrow to preserve stack details", which is on as a warning in .NET 10. A bare `throw;` is legal only inside a `catch` clause (CS0156 elsewhere); to add context instead, throw a new exception and pass the caught one as its inner exception.

code

csharp · 33 lines
csharp
#:property PublishAot=false
using System.Diagnostics;
using System.Runtime.CompilerServices;

try { Batch.WithThrowEx(); }
catch (Exception e) { Console.WriteLine("throw ex: " + Frames(e)); }

try { Batch.WithBareThrow(); }
catch (Exception e) { Console.WriteLine("throw;   : " + Frames(e)); }

static string Frames(Exception e) =>
    string.Join(" <- ", new StackTrace(e).GetFrames().Select(f => f.GetMethod()!.Name));

static class Batch
{
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static void Charge(decimal amount) =>
        throw new InvalidOperationException($"Card declined for {amount}");

    [MethodImpl(MethodImplOptions.NoInlining)]
    public static void WithThrowEx()
    {
        try { Charge(42m); }
        catch (InvalidOperationException ex) { throw ex; }
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    public static void WithBareThrow()
    {
        try { Charge(42m); }
        catch (InvalidOperationException) { throw; }
    }
}

go deeper

for a junior

Recall that throw; keeps the original stack trace and throw ex; resets it to the rethrow line. Say which one you would write in a catch block that only logs.

for a middle

Explain that both forms throw the same object and only the trace differs, name CA2200, and show the inner-exception alternative for adding context.

for a senior

Connect the choice to diagnosis: a reset trace sends an on-call engineer to the wrong method. Mention CS0156 for a bare throw outside catch and ExceptionDispatchInfo for rethrowing later.

for a principal

Treat rethrow style as something to enforce, not review: keep CA2200 at warning or error severity so throw ex; never reaches the main branch.

## What a stack trace records When code **throws** an exception, the runtime records the **stack trace**: the list of method calls from the method that threw up to the method whose `catch` block handles it. You read it through the `Exception.StackTrace` property, and `Exception.ToString()` prints it under the message. In production it is often the only clue to where a failure started, because a log line rarely carries anything else. A `catch` block that cannot fully handle an exception often wants to do something (log, roll back, count a failure) and then let the exception continue to its caller. That is a **rethrow**, and C# gives you two spellings that look alike and behave differently. ## `throw;` vs `throw ex;` | | `throw;` | `throw ex;` | |---|---|---| | What is thrown | the exception being handled | the same exception object | | `StackTrace` | kept; still starts at the original throw | reset; now starts at this line | | Message, type, `InnerException`, `Data` | unchanged | unchanged | | Where it is legal | only inside a `catch` clause | anywhere an expression of type `Exception` is available | | Analyzer | none | **CA2200**, a warning by default in .NET 10 | The C# reference states it directly: `throw;` preserves the original stack trace, while `throw e;` updates the `StackTrace` property of `e`. The object is the same; only its record of where it came from is overwritten. ## Seeing it in a payment batch In the example, `Charge` throws, and two wrapper methods catch and rethrow in the two styles. The program prints the method names from each trace (methods are marked `NoInlining` so the JIT cannot fold them away): - With `throw ex;` the trace is `WithThrowEx <- <Main>$`: the method that actually failed, `Charge`, is gone. - With `throw;` the trace is `Charge <- WithBareThrow <- <Main>$`: the original throw site is still the first frame. The SDK also printed `warning CA2200: Re-throwing caught exception changes stack information` on the `throw ex;` line while building the snippet, so the mistake is visible at build time if you read warnings. ## Where a bare `throw;` is allowed The compiler checks the placement of a bare `throw;` syntactically: 1. **Inside a `catch` block**: allowed; it rethrows the exception that block is handling. 2. **Outside any `catch` block**: error **CS0156**, "A throw statement with no arguments is not allowed outside of a catch clause". 3. **Inside a lambda or local function declared in a `catch` block**: also CS0156, because the lambda's body is a separate function that could run after the `catch` block has finished. 4. **Inside a `finally` block nested in a `catch` block**: error **CS0724**, "A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause". So a logging helper cannot rethrow on your behalf with `throw;`; the rethrow has to sit in the `catch` block itself. ## Choosing the right way to let an exception continue - **Rethrow unchanged:** `throw;`. The default when you only logged or cleaned up. - **Add context:** throw a new exception and pass the caught one as `innerException`, for example `throw new InvalidOperationException("Charging INV-7 failed", ex);`. The original keeps its own trace inside `InnerException`, and `ToString()` prints both, separated by `--- End of inner exception stack trace ---`. Note that callers now see the new type, so this is a design decision about your API rather than a rethrow. - **Rethrow later or on another thread:** a bare `throw;` is impossible there, so capture the exception with `ExceptionDispatchInfo.Capture(ex)` in the `catch` block and call `Throw()` where you need it; the original trace is restored. - **Do not catch at all:** if the block only logs and rethrows, an exception filter (`catch (Exception ex) when (Log(ex))` with `Log` returning `false`) can log without catching, so nothing is rethrown and nothing is reset. Two misreadings to avoid. `throw ex;` is not "more explicit and therefore clearer": it throws the right object with the wrong history. And `throw new Exception(ex.Message);` is worse still, because it discards the original type, trace and inner exception at once, leaving callers unable to catch the specific type and operators unable to find the failing line.

  • How do you add context to an exception in C# without losing the original stack trace?
    Throw a new exception and pass the caught one as its inner exception: `throw new InvalidOperationException("Charging INV-7 failed", ex);`. The original object, with its own untouched trace, sits in `InnerException`, and `ToString()` prints both traces separated by `--- End of inner exception stack trace ---`. Callers now catch the new type, so pick it deliberately.
  • Can a logging helper called from the catch block rethrow with a bare `throw;`?
    No. A bare `throw;` must sit lexically inside the `catch` clause; anywhere else, including a lambda declared in that block, the compiler reports CS0156. If the exception has to be rethrown later or somewhere else, capture it with `ExceptionDispatchInfo.Capture(ex)` and call `Throw()` there, which restores the original trace.
  • Does `throw ex;` change anything besides the stack trace?
    No. It is the same object, so `Message`, the runtime type, `InnerException` and `Data` are unchanged; only the recorded trace restarts at the rethrow line. That is why the bug is easy to miss: the log message looks right, but the frames that would point at the failing method are gone.

  • throw ex; and throw; are identical because the same exception object is thrown
  • throw ex; is better style because it names the exception being rethrown
  • a logging helper can rethrow with a bare throw; on the caller's behalf
  • throw new Exception(ex.Message) is a safe way to rethrow
  • the stack trace is captured when the exception object is created
open as a page

In C#, why won't a `catch (Exception)` placed before `catch (FileNotFoundException)` compile, and how does the runtime pick which catch block runs?

level: middleimportance: must knowfreq 62%

basics

~20 s

The runtime tests catch clauses top to bottom and runs only the first whose type matches and whose filter, if any, is true. A general clause first would make the specific one unreachable, so the compiler rejects it with CS0160.

open as a page

In C#, how does a `catch (TimeoutException ex) when (...)` filter differ from catching, testing a condition and rethrowing with `throw;`?

level: middleimportance: should knowfreq 42%

basics

~20 s

A when filter runs before the stack unwinds; if it returns false, the exception keeps propagating untouched, as if that catch clause were not there. Catching and rethrowing unwinds first, running inner finally blocks, and then throws again from the catch block.

open as a page

In C#, what do `ArgumentNullException.ThrowIfNull` and the other guard helpers throw, and where does the parameter name in the exception come from?

level: middleimportance: should knowfreq 45%

basics

~20 s

ThrowIfNull throws ArgumentNullException when its argument is null; the string helpers add ArgumentException for empty or whitespace, and the range helpers throw ArgumentOutOfRangeException. A [CallerArgumentExpression] parameter makes the compiler pass the argument's source text as ParamName.

open as a page

In C#, what does a `finally` block guarantee, and when does it not run or end up hiding the original exception?

level: seniorimportance: should knowfreq 48%

basics

~20 s

A finally block runs whenever control leaves its try block: normal exit, return, break, continue, goto, or an exception that something catches. Environment.FailFast, Environment.Exit, a stack overflow or a killed process skip it, and an exception thrown inside finally replaces the original.

open as a page

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%

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.

open as a page