Handle related exceptions with a C# exception filter
Use an exception filter when several exception types need the same recovery action. A catch (Exception ex) when (...) clause can accept a narrow set of failures without swallowing everything derived from Exception. C# pattern matching makes the accepted set readable.
The important decision is what recovery means. An input screen can reject a malformed number and let the user correct it. A service that cannot complete an operation should usually propagate the failure to an appropriate boundary. Catching an exception does not by itself make continued execution correct.
Run a narrow filter
Create a .NET 10 console application with dotnet new console -n FilterDemo -f net10.0. Replace Program.cs and run dotnet run --project FilterDemo from the parent directory.
using System;
using System.Globalization;
foreach (var input in new[] { "42", "not-a-number", "2147483648" }) {
try {
var value = int.Parse(input, CultureInfo.InvariantCulture);
Console.WriteLine($"Accepted {value}");
} catch (Exception ex) when (ex is FormatException or OverflowException) {
Console.WriteLine($"Rejected {input} ({ex.GetType().Name})");
}
}
try {
ParseAndReport(null);
} catch (ArgumentNullException) {
Console.WriteLine("Null propagated to the outer boundary");
}
static int ParseAndReport(string? text) {
try {
return int.Parse(text!, CultureInfo.InvariantCulture);
} catch (Exception ex) when (ex is FormatException or OverflowException) {
Console.WriteLine("Expected parsing failure");
throw;
}
}
Expected output:
Accepted 42
Rejected not-a-number (FormatException)
Rejected 2147483648 (OverflowException)
Null propagated to the outer boundary
The last call deliberately supplies null to demonstrate a failure outside the filter. The null-forgiving operator suppresses a compiler warning for that specific demonstration. It performs no runtime check. Normal production code should state whether null is allowed and validate it explicitly.
Keep recovery and diagnostics separate
FormatException and OverflowException share the input-rejection branch. ArgumentNullException does not match, so the search for a handler continues. An application defect such as a missing required dependency should not accidentally become an ordinary validation result.
If different exceptions need different actions, use separate catch clauses. Put more specific exception types before broad base types. A network timeout, an authentication failure and malformed JSON may all occur in one request, but they do not necessarily deserve the same retry, message or response code.
When a handler adds useful context and then rethrows, use throw;. It preserves the original exception stack. Writing throw ex; updates that stack and can obscure the original failure site. Creating a new domain exception is appropriate when translating an abstraction boundary, but retain the original exception as InnerException.
Keep the filter simple
Filters are evaluated before stack unwinding. Avoid mutating application state inside them. A type test or a stable error-code comparison is easier to reason about than a filter that performs I/O, changes a transaction or throws another exception. Put recovery work in the catch body.
Prefer TryParse for routine numeric validation where invalid input is expected frequently. This example uses Parse to make exception selection observable. A filter remains useful when calling an API whose contract reports the expected failures with exceptions and no suitable nonthrowing alternative exists.
Finally, keep the protected operation small enough that the filter has a clear meaning. A catch around an entire workflow can mistakenly classify an exception from an unrelated later step as an input error. Test both accepted exception types and at least one failure that must escape the handler.
References



Question provenance
This article addresses Catch multiple exceptions at once? , asked by Michael Stum on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored for current .NET. No answer text or code is reproduced.
Author: Herman Schoenfeld