0

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.

Dan Hass
  • 77
  • 8

1 Answers1

3

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.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
  • But I don't want execution to terminate from the handler. I want execution to resume in the original code. – Dan Hass Dec 12 '13 at 21:50
  • 1
    You can't. Basically, you can't wrap the "call site" for this in any scope.. because if you did, variables declared in that scope wouldn't be accessible outside of it. So if you were to wrap the attempted index access in a `try...catch` to catch the exception.. your code couldn't "continue on" .. because there'll be things declared that aren't initialized. – Simon Whitehead Dec 12 '13 at 21:56