Will Will - 1 month ago 17
C# Question

C# exception filter?

Does C# support compiling filters? How do filters even work or what do they do?

Like reflector decompiles a filter as

try
{
}
catch(Exception e) when (?)
{
}

Answer

C# did not support exception filters like VB does until C# 6. As for how they work, see Eric Lippert's "Finally" Does Not Mean "Immediately"

Starting in C# 6, exception filters are supported, as the C# FAQ demonstrates:

try { … } 
catch (MyException e) when (myfilter(e)) 
{ 
    … 
}

If the parenthesized expression after ‘if’ [now when] evaluates to true, the catch block is run, otherwise the exception keeps going.

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.

It is also a common and accepted form of “abuse” to use exception filters for side effects; e.g. logging. They can inspect an exception “flying by” without intercepting its course. In those cases, the filter will often be a call to a false-returning helper function which executes the side effects:

private static bool Log(Exception e) { /* log it */ ; return false; }
…
try { … }
catch (Exception e) when (Log(e)) {}

Thanks to Mafii for the link to the C# 6 documentation.

Comments