Exception Filtering in C# Programming
Exception filtering is a feature in C# that allows you to handle exceptions conditionally using the when keyword. This makes your error-handling logic more precise and allows for better debugging.
Why Use Exception Filtering?
- To handle exceptions based on specific conditions.
- To reduce the number of catch blocks by filtering exceptions within a single block.
- To improve code readability and maintainability.
Syntax of Exception Filtering
The when keyword is used with a catch block to specify a condition:
try { // Code that may throw an exception } catch (ExceptionType e) when (condition) { // Handle the exception if the condition is true }
Step-by-Step Example
Example 1: Basic Exception Filtering
This example demonstrates how to filter exceptions based on a condition.
using System; class Program { static void Main() { try { int number = 0; int result = 10 / number; } catch (DivideByZeroException e) when (DateTime.Now.Hour < 12) { Console.WriteLine("Caught a DivideByZeroException before noon: " + e.Message); } catch (DivideByZeroException e) { Console.WriteLine("Caught a DivideByZeroException after noon: " + e.Message); } } }
Output:
Caught a DivideByZeroException before noon: Attempted to divide by zero.
or
Caught a DivideByZeroException after noon: Attempted to divide by zero.
Example 2: Filtering Based on Exception Data
You can filter exceptions based on custom data provided during exception throwing.
using System; class Program { static void Main() { try { ThrowCustomException(); } catch (Exception e) when (e.Data["Severity"] != null && (string)e.Data["Severity"] == "High") { Console.WriteLine("High-severity exception caught: " + e.Message); } catch (Exception e) { Console.WriteLine("General exception caught: " + e.Message); } } static void ThrowCustomException() { var ex = new Exception("An error occurred."); ex.Data["Severity"] = "High"; throw ex; } }
Output:
High-severity exception caught: An error occurred.
Example 3: Exception Filtering with Custom Exceptions
Filtering can also be applied to custom exceptions to handle specific error conditions.
using System; class CustomException : Exception { public int ErrorCode { get; } public CustomException(string message, int errorCode) : base(message) { ErrorCode = errorCode; } } class Program { static void Main() { try { ThrowCustomException(); } catch (CustomException e) when (e.ErrorCode == 404) { Console.WriteLine("Resource not found: " + e.Message); } catch (CustomException e) { Console.WriteLine("Custom exception caught: " + e.Message); } } static void ThrowCustomException() { throw new CustomException("Page not found.", 404); } }
Output:
Resource not found: Page not found.
Best Practices for Exception Filtering
- Use exception filtering to avoid redundant catch blocks.
- Ensure that conditions in the when clause do not produce side effects.
- Keep the filtering logic simple and easy to understand.
Conclusion
Exception filtering is a powerful feature in C# that allows you to handle exceptions conditionally. By using the when keyword effectively, you can make your error-handling code cleaner and more efficient.