我还没有在 C# 6 中工作过,但想知道......
正如标题所说“如果Exception过滤器的过滤器抛出异常会发生什么?”。我想真正的答案是“过滤器应该以永远不会抛出异常的方式编写。”,但我们可以说它确实如此。异常是否会发生在 catch 本身内部?
try
{
throw new Exception("Forced Exception");
}
catch (Exception ex) when (MethodThatThrowsAnException())
{
WriteLine("Filtered handler 1");
}
catch (Exception ex)
{
WriteLine("Filtered handler 2");
}
Or
try
{
throw new Exception("Forced Exception");
}
catch (Exception ex) when (MethodThatThrowsAnException())
{
WriteLine("Filtered handler 1");
}
编辑:有趣的例子本节已被删除,因为该示例所基于的所谓 volatileread 中存在错误。需要进一步调查
如果过滤器内抛出异常,那么该异常将被默默地吞掉,过滤器就会失败。这会导致原始异常下降catch
情况或最终最终被向上提高。
因此,调用过滤器的代码将无法知道过滤器方法中实际上存在异常。因此,重要的是要避免可能引发异常的情况,以确保过滤器不会因此而失败。
您可以使用以下代码来验证这一点volatileread.com 的 C# 6 beta 解释器 http://volatileread.com/utilitylibrary/snippetcompiler:
public void Main ()
{
try
{
try
{
throw new Exception("Original exception");
}
catch (Exception ex)
when (Test()) // `if (Test())` in older previews
{
Console.WriteLine("Caught the exception");
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public static bool Test ()
{
throw new Exception("Exception in filter condition");
}
这导致“原始异常”出现在外部 try/catch 块中。
Update
由于我在不使用外部 try/catch 块时不理解 volatread 编译器的输出,因此我自己安装了 MS Build Tools 2015(截至本答案时仍然使用if
, not when
)并尝试了一下。事实证明,当不使用外部try/catch时,“原始异常”仍然是导致程序崩溃的原因。所以这不是过滤器异常。这似乎是 volatile 编译器的一个错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)