Let’s go through exception filters in C#. This is a powerful feature for handling exceptions conditionally.


πŸ“Œ 1. What Are Exception Filters?

  • An exception filter lets you conditionally catch an exception only if a specific condition is true.

  • Syntax:

catch (Exception ex) when (condition)
  • The when clause runs before entering the catch block.

  • If the condition is false, the exception bypasses this catch and can be handled by another catch block or propagate up the call stack.


πŸ“Œ 2. Why Use Exception Filters?

  • Avoid nested if statements inside catch blocks.

  • Catch only certain exceptions based on properties (like Message or ErrorCode).

  • Keep code clean and readable.

  • Filters don’t interfere with stack unwinding β€” the exception still behaves normally.


πŸ“Œ 3. Syntax Example

class Program
{
    static void Main()
    {
        try
        {
            int[] numbers = { 1, 2, 3 };
            int index = 5;
            Console.WriteLine(numbers[index]);
        }
        catch (IndexOutOfRangeException ex) when (ex.Message.Contains("index"))
        {
            Console.WriteLine("Index was out of range!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Other exception: " + ex.Message);
        }
    }
}
  • Only exceptions with a message containing β€œindex” are handled by the first catch.

  • Others are passed to the next catch block.


πŸ“Œ 4. Example: Conditional Logging

try
{
    // Some code
}
catch (Exception ex) when (ex is IOException || ex is TimeoutException)
{
    Console.WriteLine($"I/O or Timeout Exception: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"Other Exception: {ex.Message}");
}
  • Handles specific exceptions in one block without multiple catch statements.

πŸ“Œ 5. Key Points

FeatureNotes
when clauseEvaluates before entering catch
Multiple catchesCan bypass this catch if condition false
Stack unwindingStill occurs normally
Use caseConditional exception handling, cleaner code

πŸ“Œ 6. Analogy

  • Think of it as β€œonly catch this exception if it meets certain criteria”, like a security gate that lets through only people with certain badges.

βœ… Summary:

  • Exception filters (catch … when) let you conditionally catch exceptions.

  • Helps simplify exception handling and avoid unnecessary nesting.

  • Works with all exception types.