考虑这个简单的控制台应用程序:
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,然后查看输出。您会看到很多“未处理的异常”消息,尽管代码实际上只抛出一次。调试器导致多次抛出异常!这就是我觉得奇怪的地方。
最佳答案
你期待什么?
考虑以下方法:
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 进行调试时无法退出应用程序的原因。
如果您没有附加调试器,您的应用程序当然会因为未处理的异常而崩溃,但这是另一回事。
关于c# - 调试控制台应用程序时,Visual Studio 陷入异常报告循环。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11469826/