Today I want to discuss a good feature of C#; .i.e., exception filters. I personally like it, It allows us to add a condition onto an exception Catch Block to narrow its scope using the WHEN keyword. A catch block can specify the type of exception to catch and the type of specification is called an exception filter.
Usually, in our .Net application, we prefer to have a validation method instead.
For Items in the control, validation is possible and it is the preferred approach, but for things we cannot validate ahead of time like HTTP requests, network calls, I/O, third party, etc., exception filters may enable us to tidy our code up a little bit.
Exception filters are used to indicate that a specific catch clause matches only when that condition is true. In the below example, both catch clauses use the same exception class, but an extra condition is checked using the WHEN keyword to create a different error message.
The below example is given in Microsoft documentation.
int GetInt(int[] array, int index)
{
try
{
return array[index];
}
catch (IndexOutOfRangeException e) when (index < 0)
{
throw new ArgumentOutOfRangeException(
"Parameter index cannot be negative.", e);
}
catch (IndexOutOfRangeException e)
{
throw new ArgumentOutOfRangeException(
"Parameter index cannot be greater than the array size.", e);
}
}