AppDomain.FirstChanceException and stack overflow exception

c#

Solution

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;
    }
}

Problem

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."); } ```

Original source

Related problems