Exception filters in C#

Home » Exception filters in C#
C#

Exception filters was added in C# 6 and is a nice feature that lets you decide weather to actually catch an exception or not. The syntax works like this:

try
{
    //Code goes here
}
catch (Exception ex) when (ex.InnerException != null && ex.InnerException is SomeException)
{
    //Only catch here if the exception thrown has an inner exception of type SomeException
    //All other exceptions will have to look for a catch higher up in the call stack
}

The new syntax is when (expression) where expression evaluates to either true or false. If expression is true the exception will be catched, if false the exception will not be catched here (but hopefully somewhere higher up in the call stack).

So why is this useful? The official documentation has the explanation:

Exception filters are preferable to catching and rethrowing because they leave the stack unharmed. If the exception later causes the stack to be dumped, you can see where it originally came from, rather than just the last place it was rethrown.

Other uses

Exception filters can also be used for other things, such as logging:

try
{
    //Code goes here
}
catch (Exception ex) when (LogException(ex))
{
    //Left blank
}

private static bool LogException(Exception e)
{
    //Logg error here:
    Logger.Log(e);
    return false; 
}