← Back to C# Course | Chapter 10: Exception Handling | Lesson 5 of 6

Exception Filters (when)

In this page:

  1. Exception Filters (when)

Exception Filters (when)

A when clause adds a boolean condition to a catch block, so it only handles the exception if that condition is also true. If the condition is false, C# looks at the next catch block as if this one didn't match at all. This avoids catching an exception just to immediately re-throw it based on some check.

Note: Exception filters are useful for handling the same exception type differently based on an error code or property.

Example: Exception Filters (when)

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            throw new InvalidOperationException("critical failure");
        }
        catch (InvalidOperationException ex) when (ex.Message.Contains("critical"))
        {
            Console.WriteLine("Handled critical error: " + ex.Message);
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine("Handled general error: " + ex.Message);
        }
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.