Exception Filters in C#

Last Updated : 22 Sep, 2025

An exception filter is a boolean expression attached to a catch block using the when keyword. The catch block executes only if the filter evaluates to true. If it evaluates to false, the exception continues to propagate to the next matching catch block.

They provide more precise exception handling by filtering exceptions based on runtime conditions, without writing additional code inside the catch block.

Exception filters cannot change the exception object. They only decide whether the catch block executes.

Key Points

  • Exception filters use the when keyword with a boolean condition.
  • They allow more precise and readable exception handling.
  • Multiple filters can be applied to handle the same exception type in different scenarios.
  • Filters are evaluated before the catch block executes, so the stack remains intact if the filter is false.

Syntax

try{

// Code that may throw an exception

}

catch (ExceptionType ex) when (condition){

// Code to handle the exception if condition is true

}

  • ExceptionType: Type of exception to catch.
  • condition: Boolean expression that determines whether the catch block executes.

Example: Exception Filter

C#
using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3 };
        int index = 5;

        try
        {
            Console.WriteLine(numbers[index]);
        }
        catch (IndexOutOfRangeException ex) when (index < 0)
        {
            Console.WriteLine("Index cannot be negative.");
        }
        catch (IndexOutOfRangeException ex) when (index >= numbers.Length)
        {
            Console.WriteLine("Index exceeds array length.");
        }
    }
}

Output:

Index exceeds array length.

Explanation:

  • The first catch block is skipped because index < 0 is false.
  • The second catch block executes because index >= numbers.Length is true.
  • This allows handling different scenarios for the same exception type without nesting if statements inside the catch block.

Benefits of Exception Filters

  1. Conditional handling: Catch blocks execute only when specific conditions are met.
  2. Cleaner code: Avoids if statements inside catch blocks.
  3. Better performance: Exception filters are evaluated before the stack is unwound, reducing unnecessary overhead.
  4. Multiple scenarios: The same exception type can be handled differently based on runtime conditions.
Comment
Article Tags:

Explore