- Introduction
- Understanding Exceptions
- Handling Exceptions
- Creating and Using Custom Exceptions
- Managing Unhandled Exceptions
- Validating User Input
- Apply Your Knowledge
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
Member |
Type |
Description |
ExceptionObject |
Property |
Specifies the unhandled exception object that corresponds to the current domain |
IsTerminating |
Property |
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 logsapplication, 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.
NOTE
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
Member |
Type |
Description |
Clear() |
Method |
Removes all entries from the event log and makes it empty |
CreateEventSource() |
Method |
Creates an event source that you can use to write to a standard or custom event log |
Entries |
Property |
Gets the contents of the event log |
Log |
Property |
Specifies the name of the log to read from or write to |
MachineName |
Property |
Specifies the name of the computer on which to read or write events |
Source |
Property |
Specifies the event source name to register and use when writing to the event log |
SourceExists() |
Method |
Specifies whether the event source exists on a computer |
WriteEntry() |
Method |
Writes an entry in the event log |
STEP BY STEP 3.5 - Logging Unhandled Exceptions in the Windows Event Log
-
Add a new Windows form to the project. Name it StepByStep3_5.
-
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.
-
Switch to the code view and add the following using directive at the top of the program:
using System.Diagnostics;
-
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 = Convert.ToDecimal(txtMiles.Text); decimal decGallons = Convert.ToDecimal(txtGallons.Text); decimal decEfficiency = decMiles/decGallons; txtEfficiency.Text = String.Format("{0:n}", decEfficiency);
}
-
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. if(!EventLog.SourceExists( "Mileage Efficiency Calculator")) { EventLog.CreateEventSource( "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. eventLog.WriteEntry(unhandledException.Message); MessageBox.Show("An exception occurred: " + "Created an entry in the log file");
}
-
Insert the following Main() method:
[STAThread] 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 UnhandledExceptionEventHandler( UnhandledExceptionHandler); Application.Run(new StepByStep3_5());
}
-
Set the form as the startup object for the project.
-
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.9 You can view messages logged to an event log by using the Windows Event Viewer.
Figure 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.