调试控制台应用程序时,Visual Studio会陷入exception报告循环。 为什么?

考虑这个简单的控制台应用

using System; namespace Demo { class Program { static void Main(string[] args) { throw new Exception(); } } } 

我在Visual Studio 2010或Visual Studio 2012 Beta中的调试器下运行它。

当我这样做时,调试器自然会在exception处停止。 好的到目前为止。

但是当我按F5继续(或选择Debug | Continue)时,它会再次停止在同一个exception中。 我必须停止调试程序才能退出。 当我按下F5时,我希望程序退出。

有谁知道它为什么会这样做?

[编辑]

我已将回复标记为答案,但要查看调试器行为的奇怪后果,请考虑以下代码:

 using System; namespace Demo { class Program { static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; throw new Exception(); } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine("Unhandled Exception."); } } } 

在调试器下运行此命令并按F5一次,然后查看输出。 你会看到很多“未处理的exception”消息,尽管代码实际上只丢了一次。 调试器导致exception被多次抛出! 这就是我觉得奇怪的事情。

你有什么期望?

考虑以下方法:

 private void Test() { throw new Exception(); int u = 4; } 

抛出exception时,调试器允许您导航到调用上下文以查看程序是否捕获exception。 如果不是这种情况,它永远不会通过跳过exception退出Test方法,这就是为什么int u = 4; 无法到达。

在您的示例中,它是相同的:

 private static void Main(string[] args) { throw new Exception(); // If I'm here, I will exit the application ! // But this place is unreachable } 

由于您的exception,您无法退出Main方法范围。 这就是为什么在使用F5进行调试时无法退出应用程序的原因。

如果您没有附加调试器,您的应用程序当然会因为未处理的exception而崩溃,但这是另一个故事。

它没有这样做。 如果应用程序没有在调试器中运行,则会出现“应用程序意外退出”对话框 – 但不会在Visual Studio中。

虽然我不确定它为什么会这样,但可能是因为它让你可以选择将“当前正在执行的行”箭头​​(黄色数组)移动到应该执行的下一行并恢复操作。

否则,是的,您需要明确停止应用程序。

VS2012调试器不会继续经过未处理的exception

默认情况下,调试器会停止所有未捕获的exception(即未处理) – 这可以在“exception”对话框中更改(CTRL + ALT + E,使用我的键绑定)