Question

I have a problem that I cannot seem to solve for a project. Consider this code:

namespace TestApp
{
class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionsHandler);

        int[] a = { 0, 1, 2 };
        int y = a[6];
    }

    public static void UnhandledExceptionsHandler(object sender, UnhandledExceptionEventArgs e)
    {
        try
        {
            File.AppendAllText("Exceptions.log", (e.ExceptionObject as Exception).Message);
        }
        catch (Exception ex)
        {
            Environment.Exit(1);
        }
    }
}
}

The unhandled exception handler does in fact grab the unhandled exception as desired and write the message to log file. But on exiting the handler, the code resumes with the index out of range line: int y = a[6]. I need code to either move to the next line of code, or continue with the unhandled exception normally - in this case terminating the app. As it is, I'm stuck in an infinite loop of throw unhandled exception/hit the unhandled exception event handler.

No correct solution

OTHER TIPS

You want try..finally in your handler:

try {
    File.AppendAllText("Exceptions.log", (e.ExceptionObject as Exception).Message);
}
finally {
    Environment.Exit(1);
}

What you have now is only catching an error that occurs when writing the log file. If there is no error (which there isn't).. it will finish the method and bubble back to the original exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top