Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Exceptions and Diagnostics

Exception filters (when)

Reference for C# exception filters: the when clause on catch blocks, how filters run before unwinding, logging side effects and filtering by property.

An exception filter is a boolean expression after the when keyword on a catch clause. The catch block runs only if the exception type matches and the filter returns true. If the filter returns false, the runtime moves on to the next catch clause as if this one did not exist.

The key difference from checking inside the block and rethrowing is timing. Filters run during the first pass of exception handling, before the stack is unwound, so the original throw point, locals and stack trace are untouched. They are also the cleanest way to catch only some exceptions of a type.

C#
try { Call(); }
catch (HttpRequestException e) when (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
    // handle only 404
}

Try it

C# Selecting by property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Filters run before finally blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
catch (ExceptionType) when (condition) { ... }
catch (ExceptionType name) when (condition) { ... }
catch when (condition) { ... }
Part Description
ExceptionType The exception type that must match.
name Optional variable, available inside the filter and the block.
condition A bool expression. Evaluated each time the runtime considers this clause.

Errors / undefined behavior: if the filter itself throws, that exception is swallowed and the filter counts as false. Keep filters simple and side-effect free apart from logging.

Usage notes

  • Order matters. Clauses are tried from top to bottom; the first whose type matches and whose filter is true wins.
  • Stack preserved. Because the stack has not unwound when the filter runs, a debugger or crash dump shows the real failure site. catch followed by throw; loses nothing in the trace either, but the filter avoids the extra catch and rethrow.
  • Filters run before finally. The first pass finds a handler by running filters; the second pass unwinds and runs finally blocks. The second example shows the filter message printed before inner finally.
  • Logging without catching. A filter that logs and returns false records every exception passing through without altering the flow. Use sparingly, since it runs for exceptions that another handler may swallow.
  • Do not depend on mutable state. The filter may run before inner finally blocks have changed that state.
  • Good fits: status codes, HResult or error numbers, SocketError values, token.IsCancellationRequested, and "only if not already retried".
  • Pattern matching works: when (e.InnerException is TimeoutException) or when (e is { Code: 404 }).
  • Not for flow control of normal logic. Use ordinary if for decisions that are not about whether to catch.