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.
try { Call(); } catch (HttpRequestException e) when (e.StatusCode == System.Net.HttpStatusCode.NotFound) { // handle only 404 }
Try it
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.
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
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
truewins. - Stack preserved. Because the stack has not unwound when the filter runs, a debugger or crash dump shows the real failure site.
catchfollowed bythrow;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 runsfinallyblocks. The second example shows the filter message printed beforeinner finally. - Logging without catching. A filter that logs and returns
falserecords 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
finallyblocks have changed that state. - Good fits: status codes,
HResultor error numbers,SocketErrorvalues,token.IsCancellationRequested, and "only if not already retried". - Pattern matching works:
when (e.InnerException is TimeoutException)orwhen (e is { Code: 404 }). - Not for flow control of normal logic. Use ordinary
iffor decisions that are not about whether to catch.