繁体   English   中英

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

[英]When debugging a console app, Visual Studio gets stuck in an exception-reporting loop. Why?

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

using System;

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

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

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

但是当我按F5继续(或选择Debug | Continue)时,它再次停止在同一个异常。 我必须停止调试程序才能退出。 当我按下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一次,然后查看输出。 你会看到很多“Unhandled Exception”消息,尽管代码实际上只抛出一次。 调试器导致异常被抛出多次! 这就是我觉得奇怪的事情。

你有什么期望?

请考虑以下方法:

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

抛出异常时,调试器允许您导航到调用上下文以查看程序是否捕获异常。 如果不是这种情况,它永远不会通过跳过异常退出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
}

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

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

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

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

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

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

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

暂无
暂无

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

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