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