简体   繁体   English

如何在Visual Studio中调试时强制执行异常?

[英]How to force an exception while debugging in Visual Studio?

I am running my application in debug mode, and I would like to manually throw an exception (ie not from within the code). 我在调试模式下运行我的应用程序,我想手动抛出异常(即不在代码中)。 Is there any way to do this? 有没有办法做到这一点?

Of course, running throw new Exception("My forced exception"); 当然,运行throw new Exception("My forced exception"); in the Command or Immediate window doesn't work. 在命令或立即窗口中不起作用。

EDIT: I want the exception to be caught by the try-catch statement that surrounds the code I'm debugging. 编辑:我希望异常被我正在调试的代码周围的try-catch语句捕获。

One possible way is to break on a line and manually change a nullable variable in the code path to null just before an operation on it occurs. 一种可能的方法是在行上断开并在代码路径中的可空变量在其上的操作发生之前手动更改为null This will cause a NullReferenceException to be thrown. 这将导致抛出NullReferenceException

You could add a method similar to: 您可以添加类似于的方法:

public static void ThrowAnException(string message)
{
    throw new ApplicationException(message);
}

Then, using the Immediate window, you could call ThrowAnException("Whoops") 然后,使用立即窗口,您可以调用ThrowAnException("Whoops")

If you're running within the context of a unit test, and the point where you want the exception to originate is behind an injected interface or class, you can create a mock object that throws the exception. 如果您在单元测试的上下文中运行,并且您希望异常发起的点位于注入的接口或类的后面,则可以创建一个抛出异常的模拟对象。

The advantage of this is, once you're happy that you've replicated the error, you can construct a new unit test for your regression suite. 这样做的好处是,一旦您对复制错误感到高兴,就可以为回归套件构建一个新的单元测试。

在断点时尝试使用即时窗口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM