Exception Filters (when)
In this page:
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
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: