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.");
}
If the application does not handle the exception, the debugger is re-notified. This is known as a "second chance" exception. The debugger again suspends the application and determines how to handle this exception.
first-chance exception (plural first-chance exceptions) (computing) An exception (error condition) when handled by a debugger, such that the programmer has the first chance to study it; such an exception would otherwise proceed to a handler or (in its absence) crash the program.
The FirstChanceException event of the AppDomain class lets you receive a notification that an exception has been thrown, before the common language runtime has begun searching for exception handlers. The event is raised at the application domain level.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With