How to Use Exception Filters in C# for Precise Error Handling
In C#, use
when keyword after a catch block to add an exception filter that runs only if the condition is true. This lets you handle exceptions more precisely without nested if statements inside the catch block.Syntax
The basic syntax of an exception filter uses the when keyword after the catch clause. It allows you to specify a condition that must be true for the catch block to execute.
try: The block of code to monitor for exceptions.catch (ExceptionType ex) when (condition): Catches exceptions ofExceptionTypeonly ifconditionevaluates to true.condition: A boolean expression that filters exceptions.
csharp
try { // code that may throw } catch (ExceptionType ex) when (condition) { // handle exception only if condition is true }
Example
This example shows how to catch an ArgumentException only when its message contains the word "invalid". If the condition is false, the exception is not caught here and can be handled elsewhere or crash the program.
csharp
using System; class Program { static void Main() { try { ThrowException("invalid input"); } catch (ArgumentException ex) when (ex.Message.Contains("invalid")) { Console.WriteLine("Caught filtered exception: " + ex.Message); } catch (ArgumentException ex) { Console.WriteLine("Caught general ArgumentException: " + ex.Message); } } static void ThrowException(string message) { throw new ArgumentException(message); } }
Output
Caught filtered exception: invalid input
Common Pitfalls
Common mistakes when using exception filters include:
- Using complex or side-effecting code in the filter condition, which should be simple and fast.
- Expecting the filter to catch exceptions that do not match the type specified in
catch. - Not realizing that filters do not catch the exception if the condition is false, so another catch block or higher-level handler is needed.
csharp
try { // code } catch (Exception ex) when (LogAndReturnFalse()) { // This block never runs because filter returns false } bool LogAndReturnFalse() { Console.WriteLine("Logging in filter"); return false; // filter condition false means catch block skipped }
Output
Logging in filter
Quick Reference
Use exception filters to:
- Run catch blocks only when specific conditions are met.
- Avoid nested
ifstatements inside catch blocks. - Keep error handling code clean and readable.
Remember:
- Filters run before the catch block executes.
- If the filter condition is false, the exception is not caught here.
- Filters can access the exception object to check properties.
Key Takeaways
Use the
when keyword after catch to add a condition that filters exceptions.Exception filters let you handle exceptions only when specific conditions are true, improving code clarity.
Avoid complex logic or side effects inside filter conditions to keep them efficient and predictable.
If the filter condition is false, the exception is not caught by that catch block and can be handled elsewhere.
Exception filters help reduce nested
if statements inside catch blocks for cleaner error handling.