我正在阅读 C# 中使用 catch(..) when (..)
的过滤器表达式,但我找不到任何关于在计算表达式时抛出异常会发生什么的提及.我尝试浏览文档和规范,但要么我找不到它们,要么没有提到它们。因此,我编写了一个小程序来检查当我从 when(..)
抛出时会发生什么。我把它放在 https://dotnetfiddle.net/R7oJNp 上了
try {
Console.WriteLine("Test(): Inside Test()");
throw new Exception("thrown from Test()");
} catch (Exception) when (AlwaysThrow()) {
Console.WriteLine("Test(): caught exception in Test()");
} catch (Exception e) {
Console.WriteLine("Test(): totally skipped last catch clause, any inner exception: " + (e.InnerException?.Message ?? "nothing"));
throw;
}
我注意到的是,如果在 when(..)
中抛出异常,整个 catch(..) when (..)
block 将被跳过.它跳到下一个匹配的 catch
block ,在检查捕获的异常对象时,没有发现源自 when(..)
的异常的踪迹。
我想知道这是否是预期的行为,以及是否有关于在这种情况下应该发生什么的文档/规范的引用。跳过整个 block 并丢弃异常似乎很奇怪,因为这会使调试变得非常困难。
**编辑:** 好的,这是根据 .NET 文档的行为,但是有什么方法可以跟踪这些行为吗?我的想法是,一定不能发生异常,过滤器应该足够简单,但我们会犯错误。另外,这种行为不应该在 C# 规范中提及吗?
最佳答案
VB.Net 早在 C# 之前就支持此功能,因此您的搜索范围可能太窄了:
If an exception occurs during execution of the user-filtered expression, that exception is discarded and the filter expression is considered to have evaluated to false.
https://learn.microsoft.com/en-us/dotnet/standard/exceptions/using-user-filtered-exception-handlers
关于c# - 在 C# 中的 catch 过滤器(when 子句)内抛出的异常会发生什么情况?他们能被追踪到吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52516065/