Exception handling is one of the nightmare and the best practice for any programmer. But doesn’t matter how good the programmer is, there will be always a chance of unhandled exception daunting the users. .net 2.0+ however has a better option of handling it which is focused on recovering your application on the next start.

AppDomain.UnhandledException is an event which will allow you to handle any unhandled exceptions that would occur anywhere on your application. When you define the delegate for the above said event, it will allow you to write the code to save the current state of the application or do any custom operations so that the crash can be recovered during next recovery. However, if you wish to give user the control of handling the situation, it can be done using a excpetion dialog.

Now lets get into business.

        /// The main entry point for the application.
        static void Main()
            AppDomain.CurrentDomain.UnhandledException +=
                 new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                UnhandledExceptionMode.CatchException, true);
            // Check for application crash and recover accordingly here.
            Application.Run(new Form1());
        /// Handles the UnhandledException event of the CurrentDomain control.
        /// The source of the event.
        /// The 
        /// instance containing the event data.
        static void CurrentDomain_UnhandledException(
                     object sender, UnhandledExceptionEventArgs args)
            // Write your code to dump the crash information that can be used on recovery
             // Below code will give the user the option whether to continue
             // or to exit the application
            ThreadExceptionDialog exceptionDlg =
                      new ThreadExceptionDialog((Exception)args.ExceptionObject);


If you are looking into the handling of unexpected error, you can opt for not giving the user an option to chose what the application has to do and simply log the application state and close the application and while the user starts the next time, you can recover it. This is similar to the MS Word approach.

Or you can opt for the user to chose whether to continue or quit the application after logging the details using an exception dialog. This can be used where the application is not processing any critical data and can survive the crash.

Recovering your application from unhandled exception in .net