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

时间:2021-06-23 02:56:18

I am running my application in debug mode, and I would like to manually throw an exception (i.e. not from within the code). Is there any way to do this?

我在调试模式下运行我的应用程序,我想手动抛出异常(即不在代码中)。有没有办法做到这一点?

Of course, running 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语句捕获。

4 个解决方案

#1


45  

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. This will cause a NullReferenceException to be thrown.

一种可能的方法是在一行上断开并在代码路径中的可空变量在其上的操作发生之前将其手动更改为null。这将导致抛出NullReferenceException。

#2


9  

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”)

#3


1  

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.

这样做的好处是,一旦您对复制错误感到高兴,就可以为回归套件构建一个新的单元测试。

#4


-2  

Try to use the immediate window while you are on a break point.

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

#1


45  

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. This will cause a NullReferenceException to be thrown.

一种可能的方法是在一行上断开并在代码路径中的可空变量在其上的操作发生之前将其手动更改为null。这将导致抛出NullReferenceException。

#2


9  

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”)

#3


1  

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.

这样做的好处是,一旦您对复制错误感到高兴,就可以为回归套件构建一个新的单元测试。

#4


-2  

Try to use the immediate window while you are on a break point.

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