Log Unhandled Exceptions With AppDomain UnhandledException Event

I found this reviewing the AppDomain class and think it's so awsome I had to write about it. You know how many times users get an unhandled error in a application and don't record the information. I am sure this happens to everyone. I think it's good practive for everyone to listent to this event and log unhandled exceptions.

This will NOT stop your application from terminating but at a minimum you can record the error in a log file for reference.

I grabbed this example from the MSDN documentation:

public static void Main() {
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
    try {
        throw new Exception("1");
    } catch (Exception e) {
        Console.WriteLine("Catch clause caught : " + e.Message);
    }
    throw new Exception("2");
    // Output:
    // Catch clause caught : 1
    // MyHandler caught : 2
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args) {
    Exception e = (Exception) args.ExceptionObject;
    Console.WriteLine("MyHandler caught : " + e.Message);
}