为什么 TargetInvocationException 被 IDE 视为未捕获? [英] Why is TargetInvocationException treated as uncaught by the IDE?

查看:23
本文介绍了为什么 TargetInvocationException 被 IDE 视为未捕获?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码使用反射从对象中提取属性值.在某些情况下,属性可能会抛出异常,因为它们有空引用等.

I have some code that is using reflection to pull property values from an object. In some cases the properties may throw exceptions, because they have null references, etc.

object result;
try
{
    result = propertyInfo.GetValue(target, null);

}
catch (TargetInvocationException ex)
{
    result = ex.InnerException.Message;
}
catch (Exception ex)
{
    result = ex.Message;
}

最终代码工作正常,但是当我在调试器下运行时:

Ultimately the code works correctly, however when I am running under the debugger:

当属性抛出异常时,IDE 会进入调试器,就好像异常未被捕获一样.如果我只是点击运行,程序就会通过,并且异常作为 TargetInvocationException 出现,真正的异常在 InnerException 属性中.

When the property throws an exception, the IDE drops into the debugger as if the exception was uncaught. If I just hit run, the program flows through and the exception comes out as a TargetInvocationException with the real exception in the InnerException property.

我怎样才能阻止这种情况发生?

How can I stop this from happening?

推荐答案

这似乎是设计使然".发生的情况是您可能有菜单 ToolsOptionsDebuggingGeneralEnable Just My代码已启用.

This seems to be "by design". What happens is that you likely have menu ToolsOptionsDebuggingGeneralEnable Just My Code enabled.

As 如何:打破用户未处理的异常 声明:

As How to: Break on User-Unhandled Exceptions states:

调试异常 对话框在启用仅我的代码"打开时显示一个附加列(用户未处理异常时中断).

The DebugExceptions dialog shows an additional column (Break when an exception is User-unhandled) when "Enable Just My Code" is on.

本质上,这意味着每当异常离开您的代码边界时(在这种情况下,它会下降到 .NET 框架反射代码),Visual Studio 会中断,因为它认为异常已离开用户代码.它不知道稍后会在堆栈中返回到用户代码中.

Essentially this means that whenever the exception is leaving the boundary of your code (and in this case, it falls through down to the .NET framework reflection code), Visual Studio breaks because it thinks that the exception has left the user code. It doesn't know that it will return into the user code later in the stack.

因此有两种解决方法:在菜单 Tools 中禁用 Just My CodeOptionsDebuggingGeneral 从菜单 DebugExceptions 中的用户未处理的 .NET Framework 异常中删除复选框 对话框.

So there are two workarounds: Disable Just My Code in menu ToolsOptionsDebuggingGeneral or Remove the check box from the User-unhandled .NET Framework exceptions in menu DebugExceptions dialog.

这篇关于为什么 TargetInvocationException 被 IDE 视为未捕获?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆