> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# C# Exception Filter

An exception filter in C# is a language feature that allows a `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 the `catch` statement using the `when` contextual keyword, followed by an expression enclosed in parentheses that resolves to a `bool`.

```csharp theme={"dark"}
try
{
    // Code that may throw an exception
}
catch (ExceptionType ex) when (conditionExpression)
{
    // Executes only if the exception is of ExceptionType 
    // AND the conditionExpression evaluates to true
}
```

## 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:

1. **First Pass (Search):** The runtime traverses the call stack looking for a matching `catch` block. When it finds a matching exception type, it evaluates the `when` expression. **The stack has not yet been unwound.**
2. **Second Pass (Unwind):** If the filter evaluates to `true`, the runtime unwinds the stack to the level of the `catch` block and executes the handler.

If the filter evaluates to `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 multiple `catch` blocks for the exact same exception type, provided they are differentiated by `when` clauses. The CLR evaluates these blocks sequentially from top to bottom.

```csharp theme={"dark"}
try
{
    // Operation
}
catch (HttpException ex) when (ex.ErrorCode == 404)
{
    // Evaluated first
}
catch (HttpException ex) when (ex.ErrorCode == 500)
{
    // Evaluated second
}
catch (HttpException ex)
{
    // Unfiltered fallback; evaluated last if previous filters returned false
}
```

### Filter Exceptions

If the boolean expression inside the `when` 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

The `when` clause is not limited to simple property checks; it can invoke methods.

```csharp theme={"dark"}
catch (Exception ex) when (EvaluateExceptionState(ex))
{
    // Handler
}

private bool EvaluateExceptionState(Exception ex)
{
    // Complex logic returning a boolean
    return true; 
}
```

*Note: Because filters execute during the first pass of exception handling (before stack unwinding), invoking methods that mutate application state inside a `when` clause is considered an anti-pattern, as the state will change even if the exception is ultimately handled elsewhere.*

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor C# Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
