Exception filters in C# provide a powerful way to refine exception handling. Introduced in C# 6.0, they allow developers to specify additional conditions for catching exceptions.
Exception filters are conditions that determine whether a catch block should handle an exception. They use the when
keyword followed by a boolean expression.
The basic syntax for using exception filters is:
try
{
// Code that may throw an exception
}
catch (ExceptionType ex) when (condition)
{
// Handle the exception if the condition is true
}
The condition
can be any boolean expression, allowing for complex filtering logic.
try
{
int result = 10 / int.Parse(Console.ReadLine());
}
catch (DivideByZeroException ex) when (DateTime.Now.DayOfWeek == DayOfWeek.Monday)
{
Console.WriteLine("Cannot divide by zero on Mondays!");
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero!");
}
In this example, the first catch block only executes if it's Monday. Otherwise, the second catch block handles the exception.
try
{
// Some file operation
}
catch (IOException ex) when (ex.HResult == -2147024864)
{
Console.WriteLine("The file is being used by another process.");
}
Here, we catch a specific IOException
based on its HResult
property.
To fully understand and utilize exception filters, it's helpful to be familiar with:
Exception filters enhance C#'s exception handling capabilities, allowing for more granular and expressive error management in your applications.