Explore the Enterprise Library Exception Handling Block for .NET 2.0 : Page 2
The Enterprise Library Exception Handling Block provides all the underlying plumbing code required to handle exceptions. Stop writing repetitive exception handling code and learn how to use it in your own applications to make exception handling consistent and effective.
by Thiru Thangarathinam
May 12, 2006
Page 2 of 4
Using the Exception Handling Block
After installing the Enterprise Library, you can start writing code against the Exception Handling Block. To use the exception handling block successfully, follow these steps:
Add a reference to the Microsoft.Practices.EnterpriseLibrary.Common.dll and Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll assemblies from your solution. You do this by using the "Add Reference" option and navigating to the <Drive Name>:\Program Files\Microsoft Enterprise Library January 2006\bin folder. If you decide to use logging in conjunction with exception handling, you also need to add a reference to the Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll.
Add the necessary configuration entries to your app.config (Windows Forms) or web.config (ASP.NET application) file below the <configSections> element under the root <configuration> element as shown below:
Next, add the <exceptionHandling> element directly under the root <configuration> element. Inside the <exceptionHandling> element, you add all the exception policies. The code below shows the <exceptionHandling> element specifying the policy named "Global Policy."
Figure 1. Adding Configuration Settings: The easiest way to add configuration settings is through the Enterprise Library Configuration Tool that ships with the Enterprise Library.
The preceding settings specify a policy for handling all the exceptions. Using the <exceptionHandlers> section, you can specify a custom exception handler that will process the exception in an appropriate manner. In this case, the custom handler is implemented in a class named AppMessageExceptionHandler. You will see the implementation of the AppMessageExceptionHandler class later in this article. The postHandlingAction attribute specifies the action to take after processing the exception based on the policy. This attribute takes any of the following values: None, NotifyRethrow, and ThrowNewException.
The easiest way to add these configuration settings is to use the Enterprise Library Configuration Tool that ships with the Enterprise Library. The above settings, when viewed through the Enterprise Library Configuration tool, look as shown in Figure 1.
Import the core namespace of the exception handling block "Microsoft.Practices.EnterpriseLibrary.ExceptionHandling" in your project.
Start writing code against the classes in the above namespace.