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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13864077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:00:14  来源:igfitidea点击:

How to force an exception while debugging in Visual Studio?

c#.netvisual-studio

提问by Ryan Kohn

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.

当然,throw new Exception("My forced exception");在命令或立即窗口中运行是行不通的。

EDIT: I want the exception to be caught by the try-catch statement that surrounds the code I'm debugging.

编辑:我希望异常被围绕我正在调试的代码的 try-catch 语句捕获。

采纳答案by Ryan Kohn

One possible way is to break on a line and manually change a nullable variable in the code path to nulljust before an operation on it occurs. This will cause a NullReferenceExceptionto be thrown.

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

回答by Localghost

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

在断点处尝试使用立即窗口。

回答by Belogix

You could add a method similar to:

您可以添加类似于以下内容的方法:

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

Then, using the Immediatewindow, you could call ThrowAnException("Whoops")

然后,使用立即窗口,您可以调用ThrowAnException("Whoops")

回答by Giles Roberts

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.

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