Tuesday, November 09, 2004

When to use Exceptions in .NET

Introduction
I had seen a lot of articles and problems on .NET pointing about the need of exception problems. This small article will point of need of the exceptions and its usage.The main importance is to increase capability in right usage of exceptions in .NET and not in how to write exceptions.

Exception , Bugs and Errors ? Three different Enemies

It is a common misconception to know that developers use to think of Errors , bugs and Exceptions as the same acronym but in reality they are different. Lets see it one by one. Bugs generally arises due to programmers mistake and even the compiler are the first friend to fights against this bug by informing about the syntactical accuracies.. Though Bugs can also led to exceptions but can be avoided if we write good code. We should atleast minimize the usage of bugs by writing clear code.

Errors arises due to User's mistake. For example the user has entered the string in case of integer. Though exception can also arise due to errors but one should avoid errors by writing the good validation code. This precaution not only safe us from writing wrong exceptions but do help us in writing good coding.

Exceptions are not necessarily errors
. Whether or not an exception represents an error is determined by the application in which the exception occurred. An exception that is thrown when a file is not found may be considered an error in one scenario, but may not represent an error in another.

You should not use exceptions as a means to provide your intended functionality. For example, a user might enter an invalid user name or password while logging on to an application. While this is not a successful logon, it should be a valid and expected result, and therefore should not throw an exception. However, an exception should be generated if an unexpected condition occurs, such as an unavailable user database. Throwing exceptions is more expensive than simply returning a result to a caller. Therefore they should not be used to control the normal flow of execution through your code. In addition, excessive use of exceptions can create unreadable and unmanageable code.

Exceptions are known but unpreventable errors for eg, out of memory etc... This is the place where your exception handling comes into account and can atleast notify the user with the problem. As a good coding syle, i will always recommend you to write exception handling to deal with only unprevetable situation. Though Microsoft has really put its sincere effort in helping us dealing wiht all kind of exception which either arises due to bugs, errors or exception but you should avoid using exception handling till the time it is not required. One of the reason writing the above statement is that Exception handling is memory intensive and can also affect other application running concurently. Throwing exceptions on things like invalid arguments to an API is probably just fine, but on the other hand throwing an exception due to invalid user input, or badly formatted text from an external system, could be a bad idea. Significant use of exceptions in business logic validation is more often a bad idea than a good one,

It is often preferable to use Multiple Catch statements in a single Try block, although the placement of Catch statements can impact performance.To understand about the exception hierarchy is the formost task and one should give a deep thought before dealing with exceptions in .NET. Once an exception is caught, the processing of the remaining Catch statements is aborted. Subsequently, once the Catch clause completes processing, the Finally clause is processed if available. To make your exception handler more clear, specific and efficient , go from Specific exceptiion to Generic ones.

class ExceptionTestClass
{
public static void Main()
{
int x = 0;
try
{
int y = 100/x;
}
catch (ArithmeticException e)
{
Console.WriteLine("ArithmeticException Handler: {0}", e.ToString());
}
catch (Exception e)
{
Console.WriteLine("Generic Exception Handler: {0}", e.ToString());
}
}
}


See in this example , it is better to catch the Arithmetic exception first and then Exception class as the base exception class is System.Exception.One important thing that should be taken care is that altrhough you should put all the specific handling catch blocks but should also catch any unhandled exception through System.Exception class. See in this example, Is there any neccessity to catch the Arithmetic exception if user would have entered the value of x. In that case, Probably, it would have been checked through validation code . You demanded that user should entered any numeric non zero value, but if user has entered 0, you should checked through your validation code and rather than using the exception.

Finally : Exceptions are like Accidents

You don't know when you can met with an exception so you should have the precautionary measure. This precautionary measure is very important and approriate measure should be taken at appropriate position.For example , In case, if you will wear a helmet while you are in boat does not make sense to all.

Though i had not covered this article by giving some code example but has deal with the situation which can help developers to become judicious in the usage of the Exceptions. I hope this small article would be of great usage to all the developers trying to know where to use the exception handling or not.

1 comment:

vickey said...

Nice Article Nishith .. things are pretty clear now