【发布时间】:2012-05-28 15:40:18
【问题描述】:
我正在使用FirstChanceException 事件来记录有关任何引发的异常的详细信息。
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
Console.WriteLine("Inside first chance exception.");
};
throw new Exception("Exception thrown in main.");
}
这按预期工作。但是,如果在事件处理程序内部抛出异常,则会发生堆栈溢出,因为该事件将递归引发。
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
throw new Exception("Stackoverflow");
};
throw new Exception("Exception thrown in main.");
}
如何处理事件处理程序中发生的异常?
编辑:
有一些答案建议我将代码包装在 try/catch 块中的事件处理程序中,但这不起作用,因为在处理异常之前引发了事件。
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
try
{
throw new Exception("Stackoverflow");
}
catch
{
}
};
throw new Exception("Exception thrown in main.");
}
【问题讨论】:
-
只使用布尔字段来防止递归。
-
我不明白你为什么想要这个。第一次机会异常被处理。你到底为什么要扔另一个?
-
我不是故意扔另一个。如果我尝试记录该错误并在尝试记录该信息时引发异常,会发生什么情况?
-
@nivlam 你不应该首先记录第一次机会异常。如果处理得当,它们就不是错误。
-
@nivlam 在这种情况下,使用调试器会容易得多。 创建一个仅记录第一次机会异常的简单调试器可能会更容易。
标签: c#