Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Exception Handling in .NET 2.0

Posted by Ravi Varma Thumati on May 7, 2009

In this article we will examines the usage of Exceptions in .NET 2.0 with the help of examples and scenarios in Web and Windows.


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. 

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.

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.

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.

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.

 

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. 

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
  • 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.
  • It is a bad idea to suppress an exception.  
  • Suppressing means simply having a catch block without having any code in it
  • 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.

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. 

 [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.

About these ads

One Response to “Exception Handling in .NET 2.0”

  1. We highly appreciate your blog post. There are actually dozens of methods we could put it to really good use with the help of no effort with time and hard earned cash. Thank you very much pertaining to helping make this post answer many issues we have come across before now.

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

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: