#908 – Handling Unhandled Exceptions

An unhandled exception is one that propagates up the call stack without being caught by an exception handler in a catch block.  By default, the .NET runtime will cause a dialog to be displayed when an unhandled exception occurs.

908-001

When an unhandled exception occurs, you can’t recover from the exception.  But you can do some final logging and then terminate the application quietly by adding a handler to the AppDomain.UnhandledException event.

        static void Main(string[] args)
        {
            // Specify handler for all unhandled exceptions
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            throw new ApplicationException("Something bad happened");

            Console.ReadLine();
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception theException = (Exception)e.ExceptionObject;

            Console.WriteLine("- In the unhandled exception handler -");
            Console.WriteLine(theException.ToString());

            // Exit to avoid unhandled exception dialog
            Environment.Exit(-1);
        }

908-002

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

3 Responses to #908 – Handling Unhandled Exceptions

  1. Pingback: Dew Drop – August 14, 2013 (#1,603) | Alvin Ashcraft's Morning Dew

  2. Pingback: Windows Live Writer Tips Featured The Daily Six Pack: August 15, 2013

  3. Pingback: Dew Drop – August 15, 2013 (#1,604) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: