Unhandled Exceptions

Unhandled Exceptions

Unhandled exceptions are not handled directly in application code; they are handled in a global handler. The global handler reports the exception in an error box that offers the Debug, Send Error Report, and Don't Send buttons. For applications within the realm of a debugger, a potential unhandled exception is handled in the debugger.

What is the life cycle of an exception? Exceptions are initially categorized as first chance exceptions. If the application is attached to a debugger, the debugger is first consulted about the exception. Debuggers typically ignore first chance exceptions, and the exception is forwarded to the application next. When no debugger is present, the first chance exception is immediately sent to the application. If the application does not handle the first chance exception, the exception becomes a high-priority second chance exception. If a debugger is attached, the second chance exception is handled by the debugger. Upon finding a second chance exception, the Visual Studio debugger transfers the user to the location in the source code where the exception happened. If no debugger is present, execution is transferred to a global exception handler, which displays an error dialog box and then terminates the application. Figure 9-2 shows the life cycle of an exception.

Image from book
Figure 9-2: Life cycle of an exception

Applications can trap unhandled exceptions. The mechanism is different for Windows Forms and for Console applications. For Windows Forms, add a handler to the Application.ThreadException event. For Console applications, the handler is added to the AppDomain.UnhandledException event. Methods added to the Application.ThreadException event chain catch and handle the exception. This is an advantage when compared with AppDomain.UnhandledException. Methods added to the AppDomain.UnhandledException event can respond to an unhandled exception, but the exception is not caught. Therefore, the exception will resurface after the handlers have completed.

Do not use the unhandled exception handler to catch all exceptions. Proper application design identifies specific exceptions that an application should anticipate. Those exceptions should be caught and handled within the confines of structured exception handling. Reserve the unhandled exception method for unanticipated exceptions.


In a Windows Forms application, the windows procedure raises the Application.ThreadException event upon an unhandled exception. Subscribe to the ThreadException event to handle the unhandled exception. The subscriber is an exception handler, which prevents the application from being terminated. Do not propagate an exception caught in this manner in the unhandled exception handler. The new exception is unprotected and will likely terminate the application. After the unhandled exception handler completes, execution continues at the next message in the message pump.

Subscribe to the ThreadException event with a ThreadExceptionEventHandler delegate, which has two parameters. The object parameter is the thread object of the thread that raised the exception. The ThreadExceptionEventArg parameter of the System.Threading namespace contains the exception that was unhandled. This is the signature of the ThreadExceptionEventHandler:

ThreadExceptionEventHandler syntax:

void ThreadExceptionEventHandler(object sender,
   ThreadExceptionEventArgs e)

In the following code, the OnThreadException handler is added to the ThreadException event. The bthException_Click method raises an unhandled divide by zero exception. The unhandled exception is then handled in the OnThreadException method, which displays an informative message. Run the application in release mode for the expected results. Otherwise, the Visual Studio debugger intercedes the exception.

private void btnException_Click(object sender, EventArgs e) {
      int vara = 5, varb = 0;
      vara /= varb;

private void Form1_Load(object sender, EventArgs e) {
      Application.ThreadException += new

void OnThreadException(object sender, ThreadExceptionEventArgs e) {
      Thread t = (Thread) sender;
      Exception threadexception = e.Exception;
      string errormessage = "Thread ID: " +
          t.ManagedThreadId.ToString() +
            " [ "+ threadexception.Message + " ]";


When an unhandled exception is manifested in a Console application, the AppDomain .UnhandledException is raised. Subscribe to the event to clean up the resources of the application, such as closing files and relinquishing data connections. You might also record the unhandled exception in the event log or another location. It is important to note that the exception is not caught in the AppDomain.UnhandledException handler. After the handler finishes, the unhandled exception causes the application to be terminated. The AppDomain.UnhandledException event is triggered only in the initial application domain; it is ignored in other application domains.

Subscribe to the AppDomain.UnhandledException event with an UnhandledExceptionEventHandler delegate. The delegate has two parameters. The object parameter is the AppDomain object of the initial application domain. The UnhandledExceptionEventArgs parameter contains the specifics of the unhandled exception. This is the syntax of the UnhandledExceptionEventHandler:

UnhandledExceptionEventHandler syntax:

  • void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e)

UnhandledExceptionEventArgs offers the IsTerminating and ExceptionObject properties. IsTerminating is a Boolean property indicating the status of the application. If true, the application is terminating because of the exception. If false, the application survives the exception. In .NET 2.0, this property is always true. Unhandled exceptions on both managed and unmanaged threads terminate an application. This is cleaner than the .NET 1.1 unhandled exception model, where exceptions raised on managed threads were nonfatal. The Exception property is an exception object for the unhandled exception. Inexplicably, this property is an object type, not an Exception type. Cast the property to the Exception type to access the details of the exception.

In the following Console application, the OnUnhandledException method is added to the AppDomain.UnhandledException event. When the subsequent divide by zero exception occurs, the OnUnhandledException method is called.

using System;

namespace Donis.CSharpBook{
    public class Starter{
        public static void Main(){
                new UnhandledExceptionEventHandler(

            int vara = 5, varb = 0;
            vara /= varb;

        public static void OnUnhandledException(
                object sender, UnhandledExceptionEventArgs e) {
            string application_name=sender.ToString();
            Exception except=(Exception) e.ExceptionObject;
            string errormessage = "Application " +application_name+
                " [ Exception " + except.Message + " ]";