skip to content

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%

answer

  1. decided before anything unwinds
  2. a false filter leaves no trace
  3. inner finally blocks wait
  4. a throwing filter means false

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.

solid answer

~50 s

The runtime handles an exception in two passes: first it searches up the stack for a clause that accepts it, then it unwinds to that clause, running `finally` blocks on the way. A `when` filter runs during the search, while the frames between the throw and the `try` are still live and their `finally` blocks have not run. If it returns `false`, the search simply continues: nothing was caught or rethrown, and a crash dump still shows the original throw site. Catching, testing and rethrowing commits to the handler instead: the stack unwinds, inner `finally` blocks run, and `throw;` starts a fresh search from the catch block. That ordering makes `when (Log(ex))` with `Log` returning `false` a clean way to log without handling, but it also means the filter sees state that inner cleanup has not restored yet. A filter that itself throws counts as `false`, and its exception is discarded.

code

csharp · 36 lines
csharp
var item = new PaymentItem("INV-7", Attempts: 0);

try
{
    Process(item);
}
catch (TimeoutException ex) when (LogAndContinue(ex, item))
{
    Console.WriteLine("never: the filter returned false");
}
catch (TimeoutException)
{
    Console.WriteLine($"catch body: lock held = {item.LockHeld}");
}

static void Process(PaymentItem item)
{
    item.LockHeld = true;
    try { throw new TimeoutException("gateway timed out"); }
    finally
    {
        item.LockHeld = false;
        Console.WriteLine("inner finally: lock released");
    }
}

static bool LogAndContinue(Exception ex, PaymentItem item)
{
    Console.WriteLine($"filter: {ex.Message}, lock held = {item.LockHeld}");
    return false;
}

record PaymentItem(string Id, int Attempts)
{
    public bool LockHeld { get; set; }
}

go deeper

for a junior

Recall the syntax catch (X ex) when (condition), and that the clause handles the exception only when the condition is true.

for a middle

Explain the search and unwind passes, why a false filter leaves the exception untouched, and the logging idiom with a filter that returns false.

for a senior

Show that a filter observes state before inner finally blocks restore it, that a throwing filter silently means false, and why filters keep crash dumps useful.

for a principal

Use filters in team guidance for logging and narrow handling, and ban side effects in them beyond reading the exception and logging.

## What an exception filter is An **exception filter** is a Boolean expression after the `when` keyword on a catch clause: `catch (TimeoutException ex) when (ex.Message.Contains("gateway"))`. The clause handles the exception only if the type matches **and** the filter returns `true`. Filters let several clauses share one exception type, each taking the cases it understands, and they replace the older pattern of catching broadly, testing a property and rethrowing the cases you did not want. The two styles look equivalent in a code review. They are not, because of **when** each one runs. ## Two passes: search, then unwind When an exception is thrown, the runtime works in two phases: 1. **Search.** Starting at the throw point, it walks outward through the enclosing `try` statements and their callers, testing catch clauses. A clause's filter **runs here**, while every frame between the throw and that clause is still on the stack. 2. **Unwind.** Once a clause has accepted the exception, the runtime unwinds to it: it runs the `finally` blocks of the frames it is leaving, innermost first, and then runs the chosen catch block. A filter that returns `false` therefore changes nothing. The search moves on to the next clause, the stack is intact, the exception's trace is untouched, and if no clause accepts the exception, a debugger or crash dump shows the original throw site with all its locals. ## Seeing the order The code example models one item of a payment batch. `Process` takes a lock flag, throws `TimeoutException` and releases the flag in its `finally` block. The caller has a logging filter that returns `false`, then a plain `catch (TimeoutException)`. The SDK prints: - `filter: gateway timed out, lock held = True`: the filter ran first, while `Process` was still on the stack and its `finally` had not run. - `inner finally: lock released`: the second clause accepted the exception, and unwinding ran the inner `finally`. - `catch body: lock held = False`: only now does the catch block run. ## Filter vs catch and rethrow | | `when` filter returning `false` | catch, test, `throw;` | |---|---|---| | Inner `finally` blocks | not yet run while the filter executes | already run before the catch body | | Stack at the decision | intact, original frames live | unwound to the catch block | | Exception afterwards | continues the same search | thrown again from the catch block | | `StackTrace` | unchanged | original frames kept by `throw;` | | Debugger or dump of an unhandled exception | stops at the original throw | stops at the rethrow | The `throw;` column keeps the recorded trace, but the live frames below the catch block are gone, and with them the locals you would want in a dump. ## Rules and traps - **A filter that throws counts as `false`.** The runtime discards the filter's exception and keeps searching for the original one. The code-analysis rule CA2219 warns against raising exceptions in filters because the two outcomes cannot be told apart. In a test, a filter that dereferenced a missing `ex.Data["code"]` simply fell through to the next clause. - **The filter sees unfinished state.** Because inner `finally` blocks have not run, a filter can observe a held lock, an open transaction or a half-updated object. Keep filters to reading the exception and logging. - **The logging idiom.** `catch (Exception ex) when (Log(ex))` with `Log` returning `false` records every exception that passes, without catching it, so nothing is rethrown and nothing is reset. - **Constant filters are flagged.** A constant `false` filter gets **CS8359** (remove the clause) or **CS8360** (remove the whole `try-catch`); a constant `true` gets **CS7095**. - **Ordering.** A filtered clause may name a base type above a more specific clause, because it can decline; an unfiltered clause for the same type must come last among those for that type. ## When to choose which Use a filter when the decision depends only on the exception and cheap context: an error code, a retry counter, an environment flag. Catch and rethrow only when the handler must do work before deciding, accepting that inner cleanup has then already run and the throw site is no longer on the stack.

  • What happens if the expression inside a `when` filter throws?
    The runtime swallows the filter's exception and treats the filter as `false`, then keeps searching for a handler for the original exception. Nothing tells you the filter failed, which is why CA2219 warns against raising exceptions in filters. Keep filter expressions simple and null-safe.
  • Why is `when (Log(ex))` with `Log` returning `false` better than catching, logging and rethrowing?
    The filter logs during the search pass, so the exception is never caught: no catch block runs, nothing is rethrown, and if nothing else handles it, a crash dump still shows the original throw site with its locals. Catch-log-rethrow unwinds first, so the dump points at the rethrow and inner cleanup has already run.
  • Can a filtered `catch (Exception ex) when (...)` sit above `catch (IOException)`?
    Yes. Because the filter can return `false`, the later clause stays reachable, so the compiler does not report CS0160. Without the filter, the same order is a compile error.

A filter is a receptionist checking a visitor's badge before opening the door: if the answer is no, nothing inside the building moved. Catch and rethrow lets the visitor in, tidies the room, then walks them back out.

  • a when filter is just syntax for an if inside the catch block
  • inner finally blocks have already run when the filter executes
  • a filter that returns false resets the exception's stack trace
  • an exception thrown inside a filter replaces the original exception
  • a filter is a good place to roll back state or release locks