Explore the Enterprise Library Exception Handling Block for .NET 2.0

n an ideal world, all the code you write would always run without error. But the reality is that no matter how carefully you write your code, errors can and will occur. Therefore, it’s imperative to have an efficient, configurable exception handling framework capable of handling errors in a graceful manner. It is also important to understand that people generally gauge the effectiveness of any exception handling solution by the way it impacts the user’s experience with the application. So a good exception handling solution must not only handle errors gracefully from a user’s viewpoint, but must also provide robust configuration settings through which developers or administrators can configure the error handling behavior. Key Components of Exception Handling Block

The new Exception Handling Application Block that ships with the Enterprise Library 2.0 has undergone huge improvements since the release of the old Exception Management Application Block. To use this block effectively, you need to absorb three main concepts:

  • Exception Handling is the process of doing something with an exception when the exception is detected by your code.
  • Exception Logging is the process of logging an exception, which might include sending formatted exceptions to the event log or sending an email message. The exception handling block makes use of the Logging and Instrumentation application block for this purpose.
  • Exception Policies allow you to control exception handling and logging behaviors using external configuration files instead of baking such rules into your code. In other words, you can define the exception handling in a policy file and then change the behavior to accommodate the differing exception-handling needs during testing, debugging, and production scenarios without changing your code.

Using the exception handling block, there are three things you can do when you detect an exception in your code:

  1. You can wrap the exception in a new exception to add new context information or detail. The original exception is still available through the InnerException property when the new exception is propagated up the call stack.
  2. You can replace the exception with a new exception. You typically do this when you don’t want the details of the original exception to be propagated across an application boundary.
  3. You can log the exception. Of course, you can do this in combination with wrapping or replacing the exception, or you can log the original exception and propagate the original up the call stack.

You get the Exception Handling Block when you download the EntLib Caching Block from MSDN.

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:

  1. 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 :Program FilesMicrosoft Enterprise Library January 2006in 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.
  2. Add the necessary configuration entries to your app.config (Windows Forms) or web.config (ASP.NET application) file below the element under the root element as shown below:
  3.          
  4. If you are using logging along with exception handling, you also need to add the following settings to the element.
  5.         
  6. Next, add the element directly under the root element. Inside the element, you add all the exception policies. The code below shows the element specifying the policy named “Global Policy.”
  7.                                                                                                                                      
    ?
    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 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.

  8. Import the core namespace of the exception handling block “Microsoft.Practices.EnterpriseLibrary.ExceptionHandling” in your project.
  9. Start writing code against the classes in the above namespace.

Using the ExceptionPolicy Class
Whenever you work with the exception handling block, you will have to deal the ExceptionPolicy class, which exposes a static method named HandleException() that lets the client application interact with the Exception Handling Block. You supply the policy as an argument. The HandleException method uses a factory to create an object of type ExceptionPolicyImpl for the supplied policy. The ExceptionPolicyImpl object has a collection of ExceptionPolicyEntry objects?one object for each exception type specified in the configuration file for the named policy. For each exception type, the ExceptionPolicyEntry object contains a collection of objects that implement the IExceptionHandler interface. The collection is ordered and provides the sequence that the exception handling block uses when executing the policy. Each object that implements the IExceptionHandler interface has associated configuration information that is specific to each type of handler.

Exception handlers are .NET classes that encapsulate exception handling logic and implement the IExceptionHandler interface defined in the Exception Handling Block. By default, the Exception Handling Block includes three exception handlers:

Wrap handler. This exception handler wraps one exception around another.

Replace handler. This exception handler replaces one exception with another.

Logging handler. This exception handler the formatting of exception information, such as the message and stack trace. The logging handler gives this information to the logging block for publication.

You can extend the Exception Handling Block if required by implementing your own handlers using the Enterprise Library Configuration Tool. The nice thing about this approach is that you don’t have to modify and rebuild the application block to extend it.

Handling Exceptions Using ExceptionPolicy
To demonstrate using the Exception Handling Block, here’s a simple example. You’ll create a simple Windows forms application named ExceptionMgmtBlockExample. Create the project in Visual Studio, add the references listed earlier, and then open the default form in the designer and add a Command button named btnHandleException. Modify its Click event to look as follows:

   private void btnHandleException_Click    (object sender, EventArgs e)   {   try   {      throw new Exception       ("This is a test exception");   }   catch (Exception ex)   {      bool rethrow =        ExceptionPolicy.HandleException       (ex, "Global Policy");                          if (rethrow)      {       throw;      }   }   }

In the try block, you simply throw an exception, which the catch block will catch, invoking the HandleException() method of the ExceptionPolicy class, passing the “Global Policy” as the policy name argument. As shown in the previous section, the “Global Policy” is associated with the exception handler named AppMessageExceptionHandler, whose declaration is as follows:

   using System;   using System.Collections.Specialized;   using System.Windows.Forms;   using Microsoft.Practices.EnterpriseLibrary.Common.      Configuration;   using Microsoft.Practices. EnterpriseLibrary.Common.      Configuration.ObjectBuilder;   using Microsoft.Practices.EnterpriseLibrary.      ExceptionHandling;   using Microsoft.Practices.EnterpriseLibrary.      ExceptionHandling.Configuration;      namespace ExceptionMgmtBlockExample   {       [ConfigurationElementType        (typeof(CustomHandlerData))]      public class AppMessageExceptionHandler :        IExceptionHandler      {         public AppMessageExceptionHandler            (NameValueCollection ignore)         {         }         public Exception HandleException            (Exception exception, Guid correlationID)         {            DialogResult result = this.               ShowThreadExceptionDialog (exception);            if (result == DialogResult.Abort)               Application.Exit();            return exception;         }         private DialogResult ShowThreadExceptionDialog            (Exception e)         {            string errorMsg = e.Message +                Environment.NewLine +                Environment.NewLine;
?
Figure 2. Sample Exception: Here's the exception you get from running the sample Windows application.
return MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } } }

As you can see, the custom handler derives from the IExceptionHandler interface. The HandleException method invokes another helper method named ShowThreadExceptionDialog, which formats the exception message and displays it on the screen.

If you launch the Windows application and click on the “Handle Exception” button, you will see the message box shown in Figure 2.

Logging an Exception
In addition to handling exceptions, you can also configure the exception handling block to log the exceptions. As mentioned previously, the Exception Handling Block accomplishes this with the help of the Logging Block. To demonstrate logging, add another button named btnLogException and modify its Click event as follows:

   private void btnLogException_Click      (object sender, EventArgs e)   {      try      {         throw new Exception            ("This is a test exception");      }      catch (Exception ex)      {                         bool rethrow = ExceptionPolicy.HandleException            (ex, "Log Only Policy");                                if (rethrow)         {            throw;         }      }   }

The catch block above invokes the ExceptionPolicy.HandleException method by passing the exception object (ex) as well as the policy (the “Log Only Policy” in this case) as arguments. Similar to the exception policies, you also specify logging configuration information in the app.config or web.config file. For example, the app.config code shown below configures the “Log Only Policy” as a child element of the element:

                               ?Figure 3. Event Log Entry: The figure shows a sample application log message as seen through the Windows Event Viewer.              LoggingExceptionHandler,               Microsoft.Practices.EnterpriseLibrary.              ExceptionHandling.Logging"/>                     

The app.config file that you’ll find in the downloadable sample code for this article contains an additional example. For example purposes, the Logging Block simply logs the exceptions in the Windows Application Log, as shown in Figure 3.

Note that the logging configuration information in the app.config file controls the formatting of the log entry.

As you have seen from this article, the exception handling block obviates the need to write the exception handling plumbing code by providing a set of highly reusable classes for handling, logging and processing exceptions. By using these classes, you can reduce errors, bugs, and typos in your application and focus on the core business logic of the application thereby increasing productivity.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may

man on floor with data

DevX Quick Guide to Data Ingestion

One of the biggest trends of the 21st century is the massive surge in internet usage. With major innovations such as smart technology, social media, and online shopping sites, the internet has become an essential part of everyday life for a large portion of the population. Due to this internet

payment via phone

7 Ways Technology Has Changed Traditional Payments

In today’s digital world, technology has changed how we make payments. From contactless cards to mobile wallets, it’s now easier to pay for goods and services without carrying cash or using a checkbook. This article will look at seven of the most significant ways technology has transformed traditional payment methods.