An exception filter in C# is a language feature that allows aDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
catch block to specify a boolean condition that must evaluate to true for the exception handler to execute. Introduced in C# 6.0, it utilizes the when keyword to evaluate the state of the exception or the application environment before the Common Language Runtime (CLR) unwinds the call stack.
Syntax
The filter is appended to thecatch statement using the when contextual keyword, followed by an expression enclosed in parentheses that resolves to a bool.
Core Mechanics
Two-Pass Exception Handling and Stack Unwinding
The most critical technical distinction of an exception filter is how it interacts with the CLR’s two-pass exception handling model:- First Pass (Search): The runtime traverses the call stack looking for a matching
catchblock. When it finds a matching exception type, it evaluates thewhenexpression. The stack has not yet been unwound. - Second Pass (Unwind): If the filter evaluates to
true, the runtime unwinds the stack to the level of thecatchblock and executes the handler.
false, the runtime ignores the catch block and continues searching up the stack. Because the stack is not unwound during a false evaluation, the original crash state, local variables, and complete stack trace are preserved for debugging tools or higher-level handlers. This is mechanically superior to catching an exception, evaluating a condition inside the block, and using throw; to rethrow it, which alters the stack state.
Sequential Evaluation and Type Overloading
Exception filters allow developers to define multiplecatch blocks for the exact same exception type, provided they are differentiated by when clauses. The CLR evaluates these blocks sequentially from top to bottom.
Filter Exceptions
If the boolean expression inside thewhen clause throws an exception of its own during evaluation, the CLR catches this secondary exception silently. The runtime treats the filter as having evaluated to false and continues its search for a valid exception handler. It does not crash the application or bubble the secondary exception up the stack.
Method Invocations
Thewhen clause is not limited to simple property checks; it can invoke methods.
when clause is considered an anti-pattern, as the state will change even if the exception is ultimately handled elsewhere.
Master C# with Deep Grasping Methodology!Learn More





