Glossary / Exception filters
Exception filters
An exception filter is a when condition on a catch clause that decides whether that handler should handle a thrown exception. Filters allow contextual selection without entering the handler and rethrowing, preserving stack behavior and making catch logic more precise.
Syntax and evaluation
catch (IOException ex) when (ex.HResult == transientCode)
{
Retry();
}
The filter is evaluated when the runtime searches for a handler. If it returns false, the search continues to outer handlers. If filter evaluation itself throws, the exception is treated as a false filter in common CLR behavior; avoid side effects or exceptions in filters. Filters can inspect exception properties and local state, but should remain cheap and deterministic.
Filters differ from nested if inside catch: a false filter means this handler is not selected and stack unwinding continues to find an outer handler; a nested if has already entered the catch and may alter control flow/stack context. Filters are useful for distinguishing retryable I/O cases or logging policy.
Engineering guidance
Keep filters side-effect-free and use them to select handling, not perform recovery. Avoid overly broad filters that catch unrelated failures. Test both true and false paths and verify the outer handler receives the exception when a filter rejects it.
Interview questions
- When is a filter evaluated? During handler search before selecting the catch body.
- What if false? Search continues to another compatible handler.
- Filter vs if in catch? Filter rejection avoids entering that handler and continues stack search.
- Can a filter throw? Avoid it; CLR behavior treats filter exceptions as false rather than replacing original in typical semantics.
- What belongs in a filter? Cheap, side-effect-free contextual predicates.