无法捕获 Invoke 对已编译表达式引发的异常
在类中:
private Func<T, object> pony;
在我的函数中:
object newValue;
try {
newValue = pony.Invoke(model as T); // This is the line where I get an exception!
} catch (Exception exception) {
// This code is never run, even though I get an exception two lines up!
if(exception is DivideByZeroException) throw new DivideByZeroException("Division by zero when calculating member " + GetMemberName(), exception);
throw;
}
我希望在抛出异常时得到异常,但我在 newValue = pony.Invoke(model as T);
DivideByZeroException >。这是为什么呢?我可以做点什么吗?
这是目前在 Cassini 中运行的 asp.net mvc2 应用程序。
如果我选择在 Visual Studio 2008 中开始调试,错误将被捕获并重新抛出并附带额外信息!
问题是我显然还没有理解内部异常是如何工作的。异常被捕获,但随后只显示内部异常,这完全是另一个问题。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从编译表达式引发的异常通常由
try .. catch
构造处理,因此我预计您的代码中存在其他问题。例如,如果您尝试使用以下代码,它将按预期运行:作为旁注,您可能应该使用单独的
catch
处理DivideByZeroException
(正如我在示例中所做的那样) 。这是捕获不同类型异常的更干净且推荐的方法。您能否在不进行调试的情况下运行应用程序时检查异常是否确实未处理(例如,通过向
catch
块添加一些调试打印)?运行应用程序时会打印什么异常(毕竟,您的代码在任何情况下都会重新抛出一些异常,因此输出可能不清楚)。Exceptions thrown from a compiled expression are handled normally by the
try .. catch
construct, so I'd expect that there is some other issue in your code. If you try for example the following code, it behaves as expected:As a side note, you should probably handle
DivideByZeroException
using a separatecatch
(as I did in my example). This is a cleaner and recommended way to catch different types of exceptions.Can you check whether the exception is really unhandled when running the application without debugging (for example by adding some debug print to the
catch
block)? What exception is printed when you run the application (afterall, your code rethrows some exception in any case, so the output may not be clear).以下代码对我有用(这是在 C# 控制台应用程序中,尽管我不知道为什么它的工作方式与 ASP.NET 不同):
这将按照预期将异常的内容打印到命令行。
The following code worked for me (this is in a C# console app, although I don't know why that would work differently from ASP.NET):
This prints out the contents of the exception to the command line, as expected.
好吧,在编译表达式中执行的代码显然会生成 DivideByZeroException,对吧。其中有些东西试图除以零。那么你还期待什么呢?
请注意,调试器(尤其是 VS)可能会因异常而中断,因此您应该确保继续运行应用程序,它应该很好地到达您的 catch 块。
Well, the code executed in the compiled expression obviously generates the DivideByZeroException, right. Something tries to divide by zero in that. So what else would you expect?
Note that the debugger (especially VS) may break on exceptions, so that you should make sure to continue running the application, it should reach your catch block just fine.