Department of Education and Early Childhood Development (DEECD)
Application Development
Application Standards
Enterprise Library Application Blocks
Application Unit Testing

Exception Application Block Details

1. Introduction

Exception application block is a framework for handling exceptions ( catching, logging, presentation to the user ) in standardised way.

  • It enables developers and policy makers create a consistent strategy for processing exceptions that occur throughout the architectural layers of an enterprise application.

  • It is designed to support the typical code contained in catch statements in an application.

  • It avoids repeating code throughout identical catch blocks in an application by encapsulating 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.

    Following exception handlers included in exception handling application block.
    • 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 gives this information to the Enterprise Library Logging Application Block so that it can be published.

  • Exception Handling Application Block associates exception types with named policies. Policies specify the exception handlers that execute when the application block processes a particular exception type. Exception handlers can be chained together so that a series of them execute when the associated exception type is handled.
    Exception Handling Application Block --> Exception Policy --> Exception Type ( System.Exception Classes ) --> Exception Handler ( Custom Handler, Wrap Handler, Replace Handler and Logging Handler )

The Exception block separates the definition how an exception should be processed from the application code and moves this configuration to config file.

 

Back to top

2. When to Catch Exceptions, Exception Propagation, Hiding Exception Information and Notification

A method should catch exceptions only when it has to perform one or more of the following actions:

  • Gather information for logging.
  • Add any relevant information to the exception.
  • Execute cleanup code.
  • Try to recover.

There are three main ways to propagate exceptions:

  • Let the exception propagate automatically. With this approach, you do nothing and deliberately ignore the exception. This causes the control to move immediately from the current code block up the call stack until a catch block with a filter that matches the exception type is found.
  • Catch and rethrow the exception. With this approach, you catch and react to the exception, and clean up or perform any other required processing within the scope of the current method. If you cannot recover from the exception, you rethrow the same exception to your caller.
  • Catch, wrap, and throw the wrapped exception. As an exception propagates up the call stack, the exception type becomes less relevant. When an exception is wrapped, a more relevant exception can be returned to the caller.
Exception Wrapping and Throwing

Notification is a critical component of any exception management system. Logging is important in helping you understand what went wrong and what must be done to correct the problem, but notification informs you about the condition in the first place. Without correct notification, exceptions can go undetected.

 

Back to top

3. Different Handling Actions Based on Exception Type and Policy

Use the configuration console to create exception handling policies. An exception policy has a name and is made up of a set of exception types to be processed by that policy. Each exception type has a list of handlers that are executed sequentially.

An application can have multiple policies. This lets different parts of the application to handle the same exception types differently. For example, there could be one policy for the top of the exception handling architectural layer that specifies that exceptions should be wrapped by custom data exception types. There could be another policy for the Web user interface layer that specifies that exceptions should be logged, cleansed of any sensitive or unnecessary information, and displayed to the user.

An application passes the exception to be handled and the name of the policy that should be used to handle the exception to the Exception Handling Application Block. The application block looks at the policy to see if it has been configured to handle exceptions of that type. If it finds a match, the application block executes the series of exception handlers. The application block tries to match the exception type to the most specific type of exception listed in the configuration file. If it does not find a match, the application block looks for base class exception types.

Exception handlers (for example, handlers that log information, wrap an exception, or replace an exception) must run for each exception type. Multiple handlers can also be configured for each exception type. They run in the order they are listed in the configuration file.

Each exception handler in the chain receives the current exception. For the first handler, this is the original exception. This is the exception that the application passes to the application block. However, any handler in the chain can change the exception (for example, by wrapping it or replacing it with another exception). Subsequent handlers receive the exception that is returned from the previous handler. If a particular exception type is configured to throw the exception after executing the final handler, the exception that is returned from the last handler is thrown.

 

Back to top

4. Usage

References

To use Exception application block add the following reference assemblies to the project or to the GAC

Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll

and the core assemblies

Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.ObjectBuilder.dll

If the application configured to use Logging Exception Handler add the following reference assembly to the project or to the GAC

Microsoft.Practices.EnterpriseLibrary.Logging.dll
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll

Namespaces

The following namespace need to  be included in the classes that use the exception block.

Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
 

Back to top

5. When to use the Exception Handling Application Block

The Exception Handling Application Block is best used in situations that require uniform and flexible procedures for handling exceptions.

For example,

  • When you need consistent exception handling procedures for all components in a particular tier of an application's architecture.
  • When you need to change policies because of changing security or other operational issues.
  • When you need to log exception information or display exception information to the user.
  • Use the Exception Handling Application Block to perform only those tasks that are specific to exception handling and that do not intersect with the application's business logic.
Exception Handling Application Block Policies Example
 

Back to top

6. Exception Handling Process Diagram

Back to top

7. Exception Handling Application Block Implementation Diagram

Back to top

8. Propagating an Exception using ExceptionPolicy

Definition

The ExceptionPolicy class is the developers interface into the Exception Handling Application Block. It contains a single method that accepts the exception and the name of a preconfigured exception policy. It is the policy that determines how the exception is handled. The types of policy available are.

  • Pass the exception up the call stack upchanged.
  • Wrap the exception within another exception.
  • Replacing the exception completely with another exception.
  • Logging an exception using the Logging Application Block
  • Suppress the exception altogether.

Method - HandleException

Public Shared Function HandleException(ByVal exceptionToHandle As System.Exception, ByVal policyName As String) As Boolean

Member of: Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy

Summary:The main entry point into the Exception Handling Application Block. Handles the specified System.Exception object according to the given configurationContext.

Parameters:
exceptionToHandle: An System.Exception object.
policyName: The name of the policy to handle.

Return Values:Whether or not a rethrow is recommended. .

Example

HandleException
Try
' Run code. Catch ex As Exception Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Exception Policy") If (rethrow) Then ' Throw original exception. Throw End If End Try
 

Back to top

9. Creating a New Exception Handler Class

Definition

Application components use a policy name and an exception to indicate to the Exception Handling Application Block the behaviour to be performed. The application block provides this behaviour by executing the exception handlers configured for the policy. To allow the application block to correctly execute the handlers, all handlers must implement the IExceptionHandler interface.

To create a new exception handler class

  1. Create a new class that implements the IExceptionHandler interface.
  2. Add the class attribute ConfigurationElementType. Specify the type CustomHandlerData as the attribute parameter.
  3. Implement the HandleException method. The HandleException method contains the exception handling logic for the custom handler. When the method completes, it returns an exception. This can be the same exception passed to the HandleException method or it can be a new exception created by your handler. The exception returned by the HandleException method passes to the next exception handler's HandleException method.

Method

Implements IExceptionHandler interface

Example

Custom Exception Handler
<ConfigurationElementType(GetType(CustomHandlerData))> _
Public Class AppMessageExceptionHandler

    Public Sub New(ByVal ignore As NameValueCollection)

    End Sub

    Public Function HandleException(ByVal e As Exception, ByVal handlingInstanceID As Guid) _
                                            As Exception Implements IExceptionHandler
                                                                          .HandleException

        ' Perform processing here. The exception returned will be
        ' passed to the next exception handler in the chain.
    End Function
End Class
 

Back to top

10. Configuring Exception Policy with a PostHandlingAction for every ExceptionType

Section

PostHandlingAction is a property of the ExceptionType configuration node which determines what action will occur after the exception handling chain completes and determines what the return value for the HandleException method will be.

None. The application block executes all handlers for this exception and returns false to the application at the point that the HandleException method was invoked. Applications checking this value resume execution.

NotifyRethrow. The application block executes all handlers for this exception and returns true to the application at the point that the HandleException method was invoked. Applications checking this value rethrow the original exception.

ThrowNewException. The application block executes all handlers for this exception and throws the exception that exists after the final handler runs.

Note: Edit configuration file using Enterprise Library Configuration Console.

Example

Create "Data Access Policy" for data operations exception having ExceptionType "System.Exception".

< exceptionHandling >
    < exceptionPolicies >
        < add name="Data Access Policy" >
            < exceptionTypes >
                < add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
                         postHandlingAction="ThrowNewException"
                         name="Exception" >
                    < exceptionHandlers >

                        --------

                    </ exceptionHandlers >
                </ add >
            </ exceptionTypes >
        </add>
    </ exceptionPolicies >
</ exceptionHandling >

 

Back to top

11. Declaring exception application block configuration section-handler

Section

Add the following configuration section

Note: Edit configuration file using Enterprise Library Configuration Console.

Example

<configuration>
        <
configSections>
            <
section name="exceptionHandling"
                       
type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration .ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" />
        </
configSections>
</configuration>

 

Back to top

12. Configuring Exception Handling Application Block

Section

The sample below shows the configuration of a policy that will Log an exception, Wrap it and rethrow it as a new exception.

Exception Handling Application Block --> Exception Policy --> Exception Type ( System.Exception Classes ) --> Exception Handler ( Custom Handler, Wrap Handler, Replace Handler and Logging Handler )

Note: Edit configuration file using Enterprise Library Configuration Console.

Example for Data Access Policy

<exceptionHandling>
    <
exceptionPolicies>
        <
add name="Data Access Policy">
            <
exceptionTypes>
                <
add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
                        postHandlingAction="ThrowNewException"
                       
name="Exception">
                    <
exceptionHandlers>
                        <
add logCategory="Errors"
                              
eventId="100"
                              
severity="Error"
                              
title="Enterprise Library Exception Handling"
                             
 formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null"
                              
priority="1"
                              
type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null"
                    
          name="Logging Handler" />

                        <
add exceptionMessage="An error occurred in the Data Access layer."
                              
exceptionMessageResourceType=""
                             
 wrapExceptionType="ExceptionDemo.DataAccessLayer.DataAccessException, ExceptionDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
                              
type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WrapHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null"
                              
name="Wrap Handler" />
                    </
exceptionHandlers>
                </
add>
            </
exceptionTypes>
        </
add>
    </
exceptionPolicies>
</
exceptionHandling>

 

Back to top

13. Deployment

Guideline

The Exception Handling Application Block is comprised of two assemblies. Each assembly that belongs to the Exception Handling Application Block has a file name that begins with Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.

Additionally, the application block depends on the Enterprise Library Core. Depending on its configuration, an application that uses the application block may also require the Logging Application Block assemblies and the Data Application Block assemblies.

An application that uses the Exception Handling Application Block can be deployed in one of two configurations:

  • It can be deployed as private assemblies in the application folder hierarchy.
  • It can be deployed as shared assemblies in any file system location or in the global assembly cache
 

Back to top

14. References

http://msdn2.microsoft.com/en-us/library/system.exception(vs.71).aspx  (msdn2.microsoft.com/en-us/library/system.exception(vs.71).aspx)

http://msdn2.microsoft.com/en-us/library/ms954599.aspx  (msdn2.microsoft.com/en-us/library/ms954599.aspx)

Download Enterprise Application Block 3.1   (www.microsoft.com/downloads/details.aspx?familyid=4c557c63-708f-4280-8f0c-637481c31718&displaylang=en)

 

Back to top

15. Demo source code

The sample below demonstrates some common uses of the Exception handling Application Block. In order to run this demonstration the following prerequisites are needed.

  • Windows Message Queue (for MsmqTraceListener and Distributor Service)
  • Microsoft Enterprise Library 3.1 May 2007

To run the sample simply unzip to a known location and open the file ExceptionDemo.sln in Visual Studio .NET then read the file Readme.txt before running

Download Exception Handling Application Block sample (ZIP - 26KB)

 

Back to top