Exception Handling in .NET 2.0
page 1 of 1
Published: 18 Jan 2007
Abstract
In this article Uday examines the usage of Exceptions in .NET 2.0 with the help of examples and scenarios in Web and Windows.
by Uday Denduluri
Feedback
Average Rating: 
Views (Total / Last 10 Days): 50199/ 95

Introduction

Exceptions are unusual error conditions that occur during execution of a program or an application. Most of the programmers concentrate more towards the core functionality and, hence, handling of the exceptions is neglected. It is commonly observed practice that placing a try and catch will suffice the exception handling. But, unfortunately, that is not true. This article exposes all the exception handling strategies and the best practices in exception handling in .NET.

What is an Exception?

Exceptions are unusual error conditions that occur during execution of a program or an application. Whenever an exception is occurred the .NET runtime throws an object of type “XXXException.” All the Exceptions thrown by .NET runtime have their base class as Exception. There are varieties of system exceptions that are thrown. Please find some of the Exceptions thrown by the .NET runtime.

·         OutOfMemoryException

·         NullReferenceException

·         InvalidCastException

·         ArrayTypeMismatchException

·         IndexOutOfRangeException

·         ArithmeticException

·         DivideByZeroException

·         OverFlowException

Be Proactive rather than reactive: It is always a better practice to write code in a manner to avoid exceptions rather than catching and handling the same. This approach may not be possible for all kinds of Exception since it is tough to anticipate OutOfMemoryException and avoid the same.

How to Handle Exceptions in .NET 2.0?

In .NET we have the try and catch block that enables us to handle the exceptions.

Listing 1

try
{
// Code where we are anticipating Exceptions
}
catch (Exception)
{
// Code to Handle the Exception
}
finally// Code that needs to be executed in any case
// typically cleaning up code
}

 

The try and catch block are mandatory for handling exceptions. Finally, the block is optional. It is always a better practice to handle exceptions that are anticipated. If we are dealing with a database we need to handle the SQL Exception. The code on try should be the code that anticipates any kind of exception. It is a common practice that is observed that all the code in a function is moved to a try. Such programming should not be encouraged.

Listing 2

try
{
int i = 0;
String str = String.Empty;
Hashtable ObjHashTable = new Hashtable();
// Here the actual code
----
}
catch (Exception)
{ 
// Code Handle the Exception
}

Exceptions are caught in the Catch Block. Once an Exception is caught, there are number of ways for handling the same.

Catching an Exception (eating away the exception)

This kind of handling mechanism is the least encouraged one. The problem with the approach given below is that if an exception is caught, it is not logged. This can have serious problems to the application while diagnosing in case of any problem.

Listing 3

try
{
// Code where we are anticipating the Exception
}
catch (Exception)
{ 
//Do Nothing
// Just Eat Away the Exception
}

Re-Throwing an Exception

The handling mechanism involved here will catch an exception and will re-throw another exception. As we can see from Listing 4, UnauthorizedAccessException is caught and another exception ApplicationAccessFailedException is thrown. ApplicationAccessFailedException is a custom exception. We will deal about the custom exceptions in later sections.

Listing 4

try
{
// Code where we are anticipating the Exception
}
catch (UnauthorizedAccessException ObjUnAuthorizedException)
{
ApplicationAccessFailedException ObjApplicationAccessFailedException = new ApplicationAccessFailedException();
 
ObjApplicationAccessFailedException.InnerException = ObjUnAuthorizedEnxception;
throw ObjUnAuthorizedException;
}

Showing an Error Message to User

This kind of Exception Handling mechanism is the most commonly used mechanism. As we can see from Listing 5, in the catch block a message is shown to the user.

Listing 5

try
{
// Code where we are anticipating the Exception
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Error Message: This is the Message shown to the User");
}

The message shown to the user can be an error message, warning message or an Information message.

What are Custom Exceptions? Why do we need them?

Custom Exceptions are exceptions that are created for applying the Business rules of the Application. These exceptions are used to implement the business rules violations of the application.

Definition of Business Rules:

Business rules or business rule sets describe the operations, definitions and constraints that apply to an organization in achieving its goals. These rules are then used to help the organization to better achieve goals, communicate among principals and agents, communicate between the organization and interested third parties, demonstrate fulfillment of legal obligations, operate more efficiently, automate operations, perform analysis on current practices, etc.

For example: The minimum balance set for Savings A/C in a bank would be different from a Current A/C. Hence, while developing the application for the same the Business rule would be kept as the same.

Violation of Business Rule: Whenever a Violation of Business rule is done, it should be notified and the proper message should be shown to the user. This will be handled by a Custom Exception. Let us illustrate the same with an example.

Listing 6

private void ValidateBeforeDebit(float Amount)
{
{
if((Balance – Amount ) < MimimumBalanceNeedToHave)
{
throw new MimimumBalanceViolationForSavingsAccount("Current TransactionFailed: Mimimum Balance not available");
}
Else
{
Debit(Amount);
}
}
}

We have a method ValidateBeforeDebit (). This method ensures the minimum balance. If there is no minimum balance then a Custom Exception of the type MimimumBalanceViolationForSavingsAccount is thrown. We need to handle the method whenever we call the method.

Dos and Don’ts in Exception Handling

Before we go ahead with the Dos and Don’t of Exception handling, let us understand two types of the method. These methods are divided based on the Exception Handling strategies.

Action Listener method - This is the method in which the user initiates the action and this method is called for the same. (i.e. all the events like button click events, Constructors, etc. fall under this category) Here, the action is initiated by the user.

Supporting method – This is method that supports the Action Listener method. All the methods which are not Action listeners fall under this category.

Do’s

Don’ts

Action Listener Method needs to catch the exceptions and show some meaningful message to the user

It is a bad practice to have a single try block for the entire supporting method. Place the try block wherever applicable with appropriate catch block.

All Supporting methods need to throw the exceptions.

Never have a catch block with Exception in supporting methods simply for the sake of having it.

There should not be a catch block without anticipating an Exception. Every catch should have a reason. Simply having a catch will not suffice the problem.

 It is a bad idea to suppress an exception. Suppressing means simply having a catch block without having any code.

It is always preferable to create custom exceptions for all the business rules.

It is observed that only some kinds of exceptions are logged into the logging system. All kinds of exceptions should be sent to the logging system. It is up to the logging system to decide whether the logging should occur or not.

It is a better practice to check for the business rules rather than simply throwing an exception.

Never wait for an exception to occur and then do some recovery strategy. Try to avoid encountering exceptions.

 

Difference in Handling Exceptions in Web and Windows Application

In windows the exception handling is quite different from handling exceptions for web applications. In web applications we have an event Application_Error. This event handles all the exceptions that are not handled elsewhere in the application.

Listing 7

void Application_Error(object sender, EventArgs e)
{ 
// Code that runs when an unhandled error occurs
}

The same provision is not there in the windows application. In the widow's application the visual studio template creates a class by name Program.cs.  Program class has a static method Main. All the unhandled exceptions need to be handled in the same method.

Listing 8

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(new Form1());
}
catch (Exception)
{
// Code that runs when an unhandled error occurs
}
}

Conclusion

Exceptions are unusual error conditions that occur during execution of a program or an application. Handling exceptions properly is one of the key factors for the success of the Application development. It is a well noted fact that a developer concentrates more towards the functionality and less towards error handling. But, the functionality is incomplete without a proper Exception handling mechanism. Hence, all the enterprise applications first decide the strategy for implementing the exceptions handling and then start the coding. All the strategies of exception handling were discussed in this article.

References

http://en.wikipedia.org/wiki/Business_rules



User Comments

Title: Repeater Source Code   
Name: Arshad
Date: 4/3/2012 1:46:57 AM
Comment:
Hello hope you wil be fine.I wrote your blog it is very nice and easy to understand.Actually i am facing some proble regarding gridview.I want to implement grid view as repeater like which you have created this please help me how to write it.I am waiting your reply.Thanks
arshad.sayyed102@gmail.com this is my id.
Title: Exception Handling in .NET 2.0   
Name: Raj
Date: 2/21/2012 7:26:42 AM
Comment:
good explaination
Title: Exception Handling in .NET 2.0   
Name: Muzammil Ahmed
Date: 10/23/2009 8:58:21 AM
Comment:
No much detail is provided.This is only usefull only to biginers.
Title: Exception Handling in .NET 2.0   
Name: am
Date: 10/23/2009 8:44:43 AM
Comment:
Good
Title: Naive Reader wants real content   
Name: Naive Reader
Date: 11/9/2007 7:09:05 AM
Comment:
Why submit an article without proper proofreading? Why comment on your own work, it's simply mindblowing?!?! Where does your experience come from??? Was this written from the perspective of: "I have a few minutes to jot down what I just learned." or "I have written many articles without any experience for the fun of it, sort of like Ken Getz."
Title: A better article can be found here   
Name: Mel
Date: 11/7/2007 10:58:39 AM
Comment:
Your article misses some crucial points. Please take a look at the article below for a fuller explanation.

http://codebetter.com/blogs/karlseguin/archive/2006/04/05/142355.aspx
Title: Mr.   
Name: Niki
Date: 11/7/2007 5:46:37 AM
Comment:
I think you forgot an important rule: Never throw or catch System.Exception directly. Always catch a base class of it, so you know what kind of exception you're handling. (I think there's a FxCop rule for this, too.)
Title: Exception Handling in Asp.Net 2.0   
Name: S.S.SIVAPRASAD
Date: 9/13/2007 1:45:00 PM
Comment:
Excellent article..Plenty of stuff that I haven't learnt earlier..Superb explanation of the try and catch block but 1 point u miss was the finally block.
Please elaborate the finally block a bit.
Else everything was excellent..simply mindblowing.
Title: Exception Handling in Asp.Net 2.0   
Name: Harsimrat
Date: 8/10/2007 3:27:50 AM
Comment:
Excellent article..Plenty of stuff that I haven't learnt earlier..Superb explanation of the try and catch block but 1 point u miss was the finally block.
Please elaborate the finally block a bit.
Else everything was excellent..simply mindblowing.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 11/27/2014 8:20:10 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search