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
orErrorCode
). -
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
Feature | Notes |
---|---|
when clause | Evaluates before entering catch |
Multiple catches | Can bypass this catch if condition false |
Stack unwinding | Still occurs normally |
Use case | Conditional 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.