#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

#907 – Exceptions Thrown from Main Are Treated as Unhandled Exceptions

When an exception is thrown from a Main method and you don’t catch the exception within the Main method, the exception will be treated as an unhandled exception.  Because the Main method is the entry point, or topmost method, of your application, there is no higher level method where the exception can be handled.

When the unhandled exception occurs, the application will stop executing and display an error message.

In the example below, we throw an exception of type ApplicationException from the Main method, but do not catch the exception in Main.  The exception is dumped to the console output and we see an error dialog.

        static void Main(string[] args)
        {
            if (DateTime.Now.DayOfWeek == DayOfWeek.Monday)
                throw new ApplicationException("Sorry, I don't work on Mondays");

            Console.WriteLine("I'm running normally..");
        }

907-001

#876 – Unhandled Exceptions

If an exception is thrown while your code is executing and you don’t have a handler that catches the exception, it is considered an unhandled exception.  An unhandled exception is one that travels all the way back up the call stack without encountering a handler that catches the exception.

When an unhandled exception occurs, the application will stop executing and display an error message.

For example, if we call a method named MethodA from a console application and it throws an exception that we don’t catch, we see some information about the exception dumped to the console and an error window.

876-001

 

Here’s another example where a WPF application throws an exception when we click on a button and we don’t handle the exception:

876-002