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:
Syntax
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)
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);
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Using
catch (Exception ex) { if (...) { ... } else { throw ex; } }instead of awhenfilter, sincethrow ex;resets the stack trace while a filter leaves the original exception untouched. - Expecting a
catch ... when (condition)block to run when the condition is false; it is skipped, and the exception moves on to the nextcatchor becomes unhandled. - Putting code that can itself throw inside the
whencondition, because an exception thrown in a filter is swallowed and treated asfalse, which hides the bug.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: