Why is TargetInvocationException treated as uncaught by the IDE?

前端 未结 2 896
醉酒成梦
醉酒成梦 2020-12-01 18:10

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.<

相关标签:
2条回答
  • 2020-12-01 18:38

    EDIT: I've just tried this myself, and it looks like reflection is treated slightly differently. You might want to think of a reflection call as starting a new level of "handled" as far as the debugger is concerned: nothing is catching that exception before it gets translated and rethrown as a TargetInvocationException, so it breaks in. I don't know if there's any way of inhibiting that - but does it happen very often? If you're regularly performing lots of operations which result in exceptions, you might want to reconsider your design.


    Original answer

    Go to Debug / Exceptions... and see what the settings are. You'll see this behaviour if TargetInvocationException (or anything higher in the hierarchy) has the "Thrown" tickbox checked.

    0 讨论(0)
  • 2020-12-01 18:43

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

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题