Exception filtering
Learn catch filtering with the when clause.
Exception filtering (when)
Since C# 6 you can add a when clause to catch blocks: catch (Exception ex) when (ex.Message == "..."). This is called an exception filter. If the condition is true the catch runs; otherwise it is skipped.
Filtering lets you decide behavior based on the error content, not just the type. For example you can catch only errors with certain messages and let others bubble up. You can also use side effects like Log(ex) inside the filter.
Filter examples
You can distinguish multiple catch blocks with when. Example: catch (Exception ex) when (ex.Message.Contains("disk")) { ... } and separately catch (Exception ex) when (ex.Message.Contains("network")) { ... }. This lets you take different actions based on the message.
When the filter returns false, the catch is skipped and another catch is searched; otherwise the exception propagates. Avoid side effects in filters; they make debugging harder.
Exercise Filter with when
Define static async Task FailAsync(string msg). In its body write await Task.CompletedTask; and throw new Exception(msg);. Make Main a static async Task Main. Apply the filter with try { await FailAsync("Expected"); } catch (Exception ex) when (ex.Message == "Expected") { Console.WriteLine("Caught"); } and print.
Show example solution
In FailAsync body write await Task.CompletedTask; and throw new Exception(msg);. Make Main static async Task Main() and write try { await FailAsync("Expected"); } catch (Exception ex) when (ex.Message == "Expected") { Console.WriteLine("Caught"); }
Example solution:
using System;
using System.Threading.Tasks;
class Program
{
static async Task FailAsync(string msg)
{
await Task.CompletedTask;
throw new Exception(msg);
}
static async Task Main()
{
try
{
await FailAsync("Expected");
}
catch (Exception ex) when (ex.Message == "Expected")
{
Console.WriteLine("Caught");
}
}
}
Test yourself
-
Complete the when clause
catch (Exception ex) ____ (ex.Message == "Hata") { Console.WriteLine(ex.Message); }Show answer
catch (Exception ex) when (ex.Message == "Hata") { Console.WriteLine(ex.Message); } -
What does the when clause do?
- It adds a finally block
- It repeats the try block
- It silently swallows the exception
- It runs the catch only when the condition is true
Show answer
It runs the catch only when the condition is true — Correct. The when clause runs the catch only when true; otherwise skipped.
-
Match filtering concepts
- when (cond)
- Filters the catch
- ex.Message.Contains(...)
- Condition by message
- catch (Exception ex)
- General catch
- if it returns false
- Catch is skipped