Home > Articles

  • Print
  • + Share This
This chapter is from the book

Managing Unhandled Exceptions

The CLR-managed applications execute in an isolated environment called an application domain. The AppDomain class of the System namespace programmatically represents the application domain. The AppDomain class provides a set of events that allows you to respond when an assembly is loaded, when an application domain is unloaded, or when an application throws an unhandled exception. In this chapter, we are particularly interested in the UnhandledException event of the AppDomain class, which occurs when any other exception handler does not catch an exception. Table 3.2 lists the properties of the UnhandledExceptionEventArgs class.

Table 3.2 Important Members of the UnhandledExceptionEventArgs Class






Specifies the unhandled exception object that corresponds to the current domain



Indicates whether the CLR is terminating

You can attach an event handler with the UnhandledException event to take custom actions such as logging exception-related information. A log that is maintained over a period of time may help you find and analyze patterns with useful debugging information. There are several ways you can log information that is related to an event:

  • By using the Windows event log

  • By using custom log files

  • By using databases such as SQL Server

  • By sending email notifications

Among these ways, the Windows event log offers the most robust method for event logging because it requires minimal assumptions for logging events. The other cases are not as fail-safe; for example, an application could loose connectivity with the database or with the SMTP server, or you might have problems writing an entry in a custom log file.

The .NET Framework provides you access to the Windows event log through the EventLog class. Windows 2000 and later have three default logs—application, system, and security. You can use the EventLog class to create custom event logs. You can easily view the event log by using the Windows Event Viewer utility.


When Not to Use the Windows Event Log The Windows event log is not available on older versions of Windows, such as Windows 98. If your application needs to support computers running older versions of Windows, you might want to create a custom error log. In a distributed application, you might want to log all events centrally in a SQL Server database. To make the scheme fail-safe, you can choose to log locally if the database is not available and transfer the log to the central database when it is available again.

You should familiarize yourself with the important members of the EventLog class that are listed in Table 3.3.

Table 3.3 Important Members of the EventLog Class






Removes all entries from the event log and makes it empty



Creates an event source that you can use to write to a standard or custom event log



Gets the contents of the event log



Specifies the name of the log to read from or write to



Specifies the name of the computer on which to read or write events



Specifies the event source name to register and use when writing to the event log



Specifies whether the event source exists on a computer



Writes an entry in the event log

STEP BY STEP 3.5 - Logging Unhandled Exceptions in the Windows Event Log

  1. Add a new Windows form to the project. Name it StepByStep3_5.

  2. Place three TextBox controls (txtMiles, txtGallons, and txtEfficiency) and a Button control (btnCalculate) on the form and arrange them as shown in Figure 3.1. Add Label controls as necessary.

  3. Switch to the code view and add the following using directive at the top of the program:

    using System.Diagnostics;
  4. Double-click the Button control and add the following code to handle the Click event handler of the Button control:

    private void btnCalculate_Click(
      object sender, System.EventArgs e)
      //This code has no error checking.
      //If something goes wrong at run time,
      //it will throw an exception
      decimal decMiles =
      decimal decGallons =
      decimal decEfficiency = decMiles/decGallons;
      txtEfficiency.Text =
        String.Format("{0:n}", decEfficiency);


  5. Add the following code in the class definition:

    private static void UnhandledExceptionHandler(
      object sender, UnhandledExceptionEventArgs ue)
      Exception unhandledException =
        (Exception) ue.ExceptionObject;
      //If no event source exist,
      //create an event source.
         "Mileage Efficiency Calculator"))
          "Mileage Efficiency Calculator",
          "Mileage Efficiency Calculator Log");
      // Create an EventLog instance
      // and assign its source.
      EventLog eventLog = new EventLog();
      eventLog.Source = "Mileage Efficiency Calculator";
      // Write an informational entry to the event log.
      MessageBox.Show("An exception occurred: " +
        "Created an entry in the log file");


  6. Insert the following Main() method:

    public static void Main()
      // Create an AppDomain object
      AppDomain adCurrent = AppDomain.CurrentDomain;
      // Attach the UnhandledExceptionEventHandler to
      // the UnhandledException of the AppDomain object
      adCurrent.UnhandledException += new
      Application.Run(new StepByStep3_5());


  7. Set the form as the startup object for the project.

  8. Run the project. Enter invalid values for miles and gallons and run the program. When an unhandled exception occurs, a message box is displayed, notifying you that the exception has been logged. You can view the logged message by selecting Event Viewer from the Administrative Tools section of the Control Panel. The Event Viewer displays the Mileage Efficiency Calculator Log and other logs in the left pane (see Figure 3.9). The right pane of the Event Viewer shows the events that are logged. You can double-click an event to view the description and other properties of the event, as shown in Figure 3.10.

Figure 3.9Figure 3.9 You can view messages logged to an event log by using the Windows Event Viewer.

Figure 3.10Figure 3.10 You can view event properties for a particular event to see the event-related details.

  • If the existing exception classes do not meet your exception handling requirements, you can create new exception classes that are specific to your application by deriving them from the ApplicationException class.

  • You can use the UnhandledException event of the AppDomain class to manage unhandled exceptions.

  • You can use the EventLog class to log events to the Windows event log.

  • + Share This
  • 🔖 Save To Your Account