C# 6 features – Exception filters

C# 6 - Exception Filters

facebooktwittergoogle_pluslinkedinmail

Exception filters were already available in Visual Basic and F#, but not in C#. Recent release of C# 6 makes it equal.

Below is example of exception filters syntax in C# 6.

try
{
    // do something dangerous 
}
catch (Exception e) when (MyFilter(e))
{
    // action
}

If the expression after when  evaluates to true, the catch block is run, otherwise the exception keeps going.

Next example:

try
{
    // ...
    throw new ArgumentNullException(paramName: "someParam");
}
catch (ArgumentNullException e) when (e.ParamName == "differentParam")
{
    // Appropriate action
}

In the above, the exception type matches and condition that follows the catch expression is verified – the value of the parameter name in this example.  Here the expectation is that the catch block will not catch the exception. The exception will escape.

There was no easy alternate for getting the same functionality before C# 6. The only approach was to catch all exceptions of required type, check the exception context, and then re-throw the exception if the current state was not valid exception-catching case.

 

Use exception filters for logging

It is accepted to abuse the usage of exception filters for side effects – like logging. Filter can check an exception passing by without intercepting it. In those cases, the filter will usually be a call to a false-returning function.

private static bool Log(Exception e)
{
    // log exception
    return false;
}

// In different place
try
{
    // ...
}
catch (Exception e) when (Log(e)) { }

 

 

facebooktwittergoogle_pluslinkedinmail

Leave a comment

Your email address will not be published. Required fields are marked *