问题描述
我使用的是事件记录有关的任何细节抛出例外情况。
静态无效的主要(字串[] args)
{
AppDomain.CurrentDomain.FirstChanceException + =(发件人,EventArgs)=>
{
Console.WriteLine(内部第一次机会异常。);
};
抛出新的异常(异常主抛出。);
}
这正常工作。但是,如果有异常的事件处理中抛出,会发生堆栈溢出,因为该事件将被递归提升。
静态无效主要(字串[] args)
{
AppDomain.CurrentDomain.FirstChanceException + =(发件人,EventArgs)=>
{
抛出新的异常(#1);
};
抛出新的异常(异常主抛出。);
}
我如何处理该事件处理程序中发生的异常?
编辑:
有一个几个答案暗示我包装在try / catch块的事件处理程序中的代码,但这不起作用,因为该事件引发的异常可以处理了。
静态无效的主要(字串[] args)
{
AppDomain.CurrentDomain.FirstChanceException + =(发件人,EventArgs)=>
{
试
{
抛出新的异常(#1);
}
抓
{
}
};
抛出新的异常(异常主抛出。);
}
这是为我工作:
私人挥发性布尔_insideFirstChanceExceptionHandler;
// ...
AppDomain.CurrentDomain.FirstChanceException + = OnFirstChanceException;
// ...
私人无效OnFirstChanceException(对象发件人,FirstChanceExceptionEventArgs参数)
{
如果(_insideFirstChanceExceptionHandler)
$ { b $ b //防止递归如果异常是这种方法
返回内抛出;
}
_insideFirstChanceExceptionHandler = TRUE;
试
{
//代码可能抛出一个异常
}
抓
{
//你必须赶上内所有异常这种方法
}
终于
{
_insideFirstChanceExceptionHandler = FALSE;
}
}
I'm using the FirstChanceException event to log details about any thrown exceptions.
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
Console.WriteLine("Inside first chance exception.");
};
throw new Exception("Exception thrown in main.");
}
This works as expected. But if an exception is thrown inside the event handler, a stack overflow will occur since the event will be raised recursively.
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
throw new Exception("Stackoverflow");
};
throw new Exception("Exception thrown in main.");
}
How do I handle exceptions that occur within the event handler?
Edit:
There's a few answers suggesting that I wrap the code inside the event handler in a try/catch block, but this doesn't work since the event is raised before the exception can be handled.
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
try
{
throw new Exception("Stackoverflow");
}
catch
{
}
};
throw new Exception("Exception thrown in main.");
}
This is working for me:
private volatile bool _insideFirstChanceExceptionHandler;
// ...
AppDomain.CurrentDomain.FirstChanceException += OnFirstChanceException;
// ...
private void OnFirstChanceException(object sender, FirstChanceExceptionEventArgs args)
{
if (_insideFirstChanceExceptionHandler)
{
// Prevent recursion if an exception is thrown inside this method
return;
}
_insideFirstChanceExceptionHandler = true;
try
{
// Code which may throw an exception
}
catch
{
// You have to catch all exceptions inside this method
}
finally
{
_insideFirstChanceExceptionHandler = false;
}
}
这篇关于AppDomain.FirstChanceException和堆栈溢出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!