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

Exception Filters (when)

An exception filter adds a condition to a catch, like a goalkeeper who only stops shots aimed at one corner. The catch only handles an error when the extra condition is true.

In this page:

  1. Exception Filters (when)
Syntax
csharp
catch (ExceptionType ex) when (condition)
{
    // handled only if condition is true
}

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);
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using catch (Exception ex) { if (...) { ... } else { throw ex; } } instead of a when filter, since throw ex; resets the stack trace while a filter leaves the original exception untouched.
  2. Expecting a catch ... when (condition) block to run when the condition is false; it is skipped, and the exception moves on to the next catch or becomes unhandled.
  3. Putting code that can itself throw inside the when condition, because an exception thrown in a filter is swallowed and treated as false, which hides the bug.
🔒

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.