Introduction to the Exception Handling Application Block

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.

This topic includes a series of brief sections that provide information to help you decide whether the Exception Handling Application Block is suitable for your requirements. This topic includes the following sections:

  • Common Scenarios
  • Using Exception Handlers
  • Using Exception Policies
  • Example Application Code
  • When to Use the Exception Handling Application Block

In addition to this introductory material, the documentation contains the following topics:

For details of the system requirements for the Exception Handling Application Block, see System Requirements. For details of the dependencies for the Exception Handling Application Block, see Application Block Dependencies.

Common Scenarios

The Exception Handling Application Block is designed to address the most common tasks developers face when they write applications that use exception handling. These tasks are arranged according to scenarios. Each scenario gives an example of a real-world situation, discusses the exception handling functions the situation requires, and shows the code that accomplishes the task.

The goal of arranging these tasks according to scenarios is to give the code some context. Instead of displaying an isolated group of methods, with no sense of where they can best be used, scenarios provide a setting for the code and describe situations that are familiar to many developers whose applications must handle exceptions.

The scenarios are the following:

Using Exception Handlers

The Exception Handling Application Block is designed to support the typical code contained in catch statements in application components. Instead of repeating this code (such as logging exception information) throughout identical catch blocks in an application component, the application block allows developers to encapsulate this logic as reusable exception handlers. Exception handlers are .NET classes that encapsulate exception handling logic and implement the Exception Handling Application Block interface named IExceptionHandler. The Exception Handling Application Block includes four 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 formats exception information, such as the message and the stack trace. Then the logging handler passes this information to the Enterprise Library Logging Application Block so that it can be published.
  • Fault Contract Exception Handler. This exception handler is designed for use at Windows Communication Foundation (WCF) service boundaries, and generates a new Fault Contract from the exception.

Users can extend the Exception Handling Application Block by implementing their own handlers. The Enterprise Library configuration tools provide the ability to configure the Exception Handling Application Block to use custom handlers. Developers do not have to modify the application block source code or rebuild the application block.

Using Exception Policies

The Exception Handling Application Block lets you associate exception types with named policies. You do this by using the configuration tools. Policies specify the exception handlers that execute when the application block processes a particular exception type. You can chain these handlers together so that a series of them execute when the associated exception type is handled. The following are some examples of named policies and descriptions of what they might provide:

  • Base policy. This policy logs the exception and rethrows the original exception.
  • Secure policy. This policy logs the exception, replaces the original exception with a custom exception, and throws the new exception.
  • Expressive policy. This policy wraps the original exception inside another exception and throws the new exception.

Example Application Code

The following code shows how to execute the policy named "Data Access Policy" when an exception occurs.

try
{
  // Run code.
}
catch(Exception ex)
{
  bool rethrow = ExceptionPolicy.HandleException(ex, " Data Access Policy");
  if (rethrow)
    throw;
}
'Usage
Try
  ' Run code.
Catch ex As Exception
  Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, " Data Access Policy")
  If (rethrow) Then
    Throw
  End If
End Try

Note

If you use the Unity Integration approach to create instances of objects from the Exception Handling Application Block, you must use the non-static façade named ExceptionManager. This class exposes the same API as the ExceptionPolicy class static façade. For more information about using the Unity Application Block to create and inject instances of Enterprise Library objects, see Creating Objects Using the Unity Application Block.

When to Use the Exception Handling Application Block

For information about how to develop exception management strategies, see the Design Guidelines for Exceptions. Although it does not specifically discuss the Exception Handling Application Block, it can help you to define a clear, consistent approach to handling exceptions. Use the Exception Management Application Block to help implement your strategy.

The Exception Handling Application Block is best used in situations that require uniform and flexible procedures for handling exceptions. For example, you might want consistent exception handling procedures for all components in a particular tier of an application's architecture. In addition, because of changing security or other operational issues, you might want the ability to change policies as needed, without requiring changes to the application source code. The Exception Handling Application Block, in conjunction with the Enterprise Library configuration tools, lets you accomplish both tasks.

For example, you could use the configuration tools to define a policy that uses handlers to replace exceptions that contain sensitive information with versions that do not include that information. The application block then implements this policy across the components that contain code that specifies this policy should be used.

The Exception Handling Application Block is not limited to cross-tier applications. It can also be used within a particular application. For example, you can define policies that log exception information or display exception information to the user.

In either case, policies are configured without changing the application's code. This makes them easy to maintain or change when new situations occur. Note that, in all cases, you should use the application block to perform only those tasks that are specific to exception handling and that do not intersect with the application's business logic. For example, you can remove the handlers that log an exception or wrap one exception in another without affecting such basic capabilities as updating a customer database.

Figure 1 illustrates examples of cross-layer and single-application component exception handling.

Ff649923.7fb1f36f-86df-4367-b2a9-3b311efe51ed(en-us,PandP.10).png

Figure 1
Examples of exception handling policies

In this example, exceptions that occur in the data access layer are logged and then wrapped inside another exception that provides more meaningful information to the calling layer. Within the business component layer, the exceptions are logged before they are propagated. Any exceptions that occur in the business component layer and that contain sensitive information are replaced with exceptions that no longer contain this information. These are sent to the user interface (UI) layer and displayed to the user.

Without the Exception Handling Application Block, typical exception handling code for a data access component might look like the following example.

Note

The code does not include implementations of the custom DataAccessException exception type, or the RunQuery, FormatException, and the Logging.Log methods. These methods represent typical ways to retrieve a DataSet and to log information.

DataSet customersDataSet;
try
{
  customersDataSet = RunQuery("GetAllCustomers");
}
catch(Exception ex)
{
  string formattedInfo = FormatException(ex);
  Logging.Log(formattedInfo);
  throw new DataAccessException("Database access failure for query GetAllCustomers", e);
}
'Usage
Dim customersDataSet As DataSet

Try
  customerDataSet = RunQuery("GetAllCustomers")
Catch ex As Exception
  Dim formattedInfo As String = FormatException(ex)
  Logger.Log(formattedInfo)
  Throw New DataAccessException("Database access failure for query GetAllCustomers", e)
End Try

Code similar to this would be repeated in all the routines that perform different data access queries. To change the behavior of the exception handling code, you must update each routine that contained this code.

On the other hand, with the Exception Handling Application Block, the same application would have the following code.

Note

The code does not include an implementation of the RunQuery method. This method represents a typical way to retrieve a DataSet.

DataSet customersDataSet;

try
{
  customersDataSet = RunQuery("GetAllCustomers");
}
catch(Exception ex)
{
  bool rethrow = ExceptionPolicy.HandleException(ex, "Data Access Policy");
  if (rethrow)
    throw;
}
'Usage
Dim customersDataSet As DataSet

Try
  customerDataSet = RunQuery("GetAllCustomers")
Catch ex As Exception
  Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Data Access  Policy")
  If (rethrow) Then
    Throw
  End If
End Try

The behavior of the exception handling code is determined by an exception handling policy named Data Access Policy. The application would have configuration settings for the Data Access Policy to indicate that exceptions of type System.Exception are passed to the Logging Exception Handler for the Exception Handling Application Block. To change the behavior of the exception handling code, you change configuration information only; you do not have to update application source code.

The Exception Handling Application Block is a complement to exception handling recovery code; it is not a replacement for it. If exceptions occur because of truly unusual circumstances, it can be impossible for an application to recover gracefully and finish the unit of work it has started. However, it is sometimes possible to recover. An example is an exception that occurs because a file is locked. The recovery code might direct the application to retry the file after waiting for some period of time. In such cases, exception handling recovery code should be implemented within the application code; it should not be implemented as a handler used by the Exception Handling Application Block. This is because it requires access to local variables, parameters, and other contextual data. This data is out of scope and inaccessible to handlers run by the Exception Handling Application Block.