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

Mat*_*son 3 c# visual-studio-2010

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

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            throw new Exception();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在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.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在调试器下运行此命令并按F5一次,然后查看输出.你会看到很多"Unhandled Exception"消息,尽管代码实际上只抛出一次.调试器导致异常被抛出多次!这就是我觉得奇怪的事情.

ken*_*n2k 5

你有什么期望?

请考虑以下方法:

private void Test()
{
    throw new Exception();  
    int u = 4;
}
Run Code Online (Sandbox Code Playgroud)

抛出异常时,调试器允许您导航到调用上下文以查看程序是否捕获异常.如果不是这种情况,它永远不会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
}
Run Code Online (Sandbox Code Playgroud)

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

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