Introduction to Exception Handling Application Block

Posted: August 30, 2011 in Dotnet basics

Introduction to Exception Handling Block
Application blocks are Microsoft recommended patterns and practices which address some of the most common scenarios like logging, caching, exception handling, dependency injection and so on. All the application blocks are bundled together under an umbrella called as the Microsoft Enterpise Library. The current version of Enterprise Library is 5.0 (http://msdn.microsoft.com/en-us/library/ff648951.aspx).
Why use Enterprise Library ?
1. Address most common scenarios
2. Can be added to any application easily
3. It is collection of reusable components and best practices
4. Is configuration driven
5. They can be easily extended
I wil focus on Exception Handling Block in this article.
Steps to include Exception Handling Block :
1. Download Enterprise Library 5.0
2. Add reference to the following dlls :
Microsoft.Practices.EnterpriseLibrary.Common and Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.

3. Within your class, include namespaces :

using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

4. Then, policies need to be defined for your application
Policies may be like whether you want to rethrow exception or throw new exception or just handle the exception. This is done by setting postHandlingAction attribute. We can also have handlers associated with the policy like if we are rethrowing an exception what should be the new exception, should we wrap the exception or should we replace the exception. We can as well log the exception to a file or database. Again there are lot of extensible features.

The beauty however lies in the fact that this is completely configuration driven. There is a tool called “EntLibConfig.exe” within the downloaded Enterprise Library folder which has UI for configuring all of the Enterprise Libraries.

5. Once policies are defined, then we have to get handle to instance of appropriate classes (Exception Manager here) and then use it accordingly. The code snippet will be as shown below :

try
{
_input1 = Convert.ToInt32(textBox1.Text);
_input2 = Convert.ToInt32(textBox2.Text);
}
catch (Exception ex)
{
var exceptionManager = EnterpriseLibraryContainer.Current.GetInstance();
exceptionManager.HandleException(ex, “UIPolicy”);
}

Here UIPolicy is a defined policy for exception handling.
I have enabled Logging using Logging Application Block.

Appconfig

Happy coding!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s