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 (?) { }
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; eg 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.
Since C# 6 you can now do this.
try { … }
catch (MyException e) when (myfilter(e))
{
…
}
This is different from using an if
statement from within the catch
block, using exception filters will not unwind the stack.
C#中的异常过滤器支持在C#6(Visual Studio“Dev14”)中引入:
try
{
throw new ApplicationException("1");
}
catch (ApplicationException ex) when (ex.Message == "2")
{
// this one won't execute.
}
catch (ApplicationException ex) when (ex.Message == "1")
{
// this one will execute
}
链接地址: http://www.djcxy.com/p/25862.html
上一篇: 在现代Python中声明自定义异常的正确方法是什么?
下一篇: C#异常过滤器?