Click here to Skip to main content
15,881,838 members
Articles / Operating Systems / Windows
Article

When to use exceptions

Rate me:
Please Sign up or sign in to vote.
1.03/5 (40 votes)
24 Nov 200410 min read 64.4K   11   11
When to use exceptions

Introduction

I had seen a lot of articles and problems of NET pointing about the need of exception problems and when should we use it. If you are novice in Exception and need to know how to use the exception, you can use the following link http://support.microsoft.com/kb/816157/EN-US/  to get started. 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. When a method encounters an abnormal condition (an exception condition) that it can't handle itself, it may throw an exception. Throwing an exception is like throwing a beeping, flashing red ball to indicate there is a problem that can't be handled where it occurred. Somewhere, you hope, this ball will be caught and the problem will be dealt with. Exceptions are caught by handlers positioned along the thread's method invocation stack. If the calling method isn't prepared to catch the exception, it throws the exception up to its calling method, and so on. If one of the threads of your program throws an exception that isn't caught by any method along the method invocation stack, that thread will expire. When you program in .NET, you must position catchers (the exception handlers) strategically, so your program will catch and handle all exceptions from which you want your program to recover.

When to Use Exceptions<o:p>

When should you throw an exception? The answer can be summed up in one guideline:

If your method encounters an abnormal condition that it can't handle, it should throw an exception. <o:p>

Unfortunately, though this guideline may be easy to memorize and may sound impressive when you recite it at parties, it doesn't clear up the picture too much. It actually leads to a different question: What is an "abnormal condition?" <o:p>

That, it turns out to be a million dollar question. Deciding whether or not a particular event qualifies as an "abnormal condition" is a subjective judgment. The decision is not always obvious. It's one reason they pay you the big bucks. <o:p>

A more helpful rule of thumb could be: <o:p>

Avoid using exceptions to indicate conditions that can reasonably be expected as part of the typical functioning of the method. <o:p>

An abnormal condition, therefore, would be any condition that wouldn't reasonably be expected as part of the "normal functioning" of a method. To help you get a feel for what I mean by "normal functioning of a method," allow me to give a few examples<o:p>

Exception, Bugs and Errors ? Three different Enemy

 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. Let’s see it one by one. Bugs generally arise due to programmer’s mistake and even the compiler is 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 at least minimize the usage of bugs by writing clear code.

Errors arise 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.

Once a CLR has begun to execute a block of code -- the statements between two matching curly braces -- it can exit that block in any of several ways. It could, for example, simply execute past the closing curly brace. It could encounter a break, continue, or return statement that causes it to jump out of the block from somewhere in the middle. Or, if an exception is thrown that isn't caught inside the block, it could exit the block while searching for a catch clause. <o:p>

Given that a block can be exited in many ways, it is important to be able to ensure that something happens upon exiting a block, no matter how the block is exited. For example, if you open a file in a method, you may want to ensure the file gets closed no matter how the method completes. In .NET, you express such a desire with a finally clause. <o:p>

To use a finally clause, you simply: (1) Enclose the code that has multiple exit points in a try block; and (2) place the code that must be executed when the try block is exited in a finally clause.

Exceptions are known but unpreventable errors for e.g., out of memory etc... This is the place where your exception handling comes into account and can at least notify the user with the problem.  As a good coding syle,i will always recommend you to write exception handling to deal with only unpreventable situation. Though Microsoft has really put its sincere effort in helping us dealing with 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 reasons writing the above statement is that Exception handling is memory intensive and can also affect other application running concurrently. 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,

When using exceptions, you should establish a policy for when to throw an exception, what to put into the exception, and when to create a custom exception. Exceptions have performance implications because you incur overhead when creating and handling them. Thus, if it you can check whether a particular exception state would occur prior to executing the code, you should check for the condition first rather than allowing an exception to occur—especially if you're executing in a loop.<o:p>

For example, when you want to open a file, you can avoid the FileNotFoundException by using the File.Exists method to determine whether or not the file exists prior to opening the file. Along the same lines, you should avoid using exceptions for common or expected error conditions. Rather than throwing an exception, you should consider returning null or some other sort of error condition. As an example, rather than throwing an exception, String.IndexOf returns -1 if the desired match string does not exist because it is fairly common for the match string not to exist in the source string. An example of where this isn't followed and probably should be is when it comes to checking whether a particular object is a number, which is a common step in many applications that accept input. The only way to check is to try and convert the object to a number with one of the methods in System.Convert, which throws an exception if the object is not a number. Hopefully, Microsoft will address this in future versions of the .NET Framework.<o:p>

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 foremost 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 exception to Generic ones.

class ExceptionTestClass
{
public static void <st1:place>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 although 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 necessity 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 meet with an exception so you should have the precautionary measure. This precautionary measure is very important and appropriate 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. So you should wear life jackets while in boat and helmet while in bike. So appropriate exception handling is needed.

All too often, programmers put cryptic or unhelpful information into exceptions. Messages such as "An error has occurred." are not all that helpful. A common tendency is to catch an exception when it occurs and then throw a new exception in its place. If you don't include enough relevant information in your exception, it will be hard for other programmers to determine what caused it or what to do about it. Always test out the relevance of the contained information by logging it to wherever you trap your application logs. The litmus test is whether or not the log provides enough information to diagnose and debug the exception. Additionally, if you don't have anything relevant to add to the exception thrown, nor are you planning to recover from it in the area where it is being trapped, then why trap and re-throw it in the first place? You're better off just allowing the exception to pass back up the calling stack unchanged.

  Though i had not covered this article by giving some code example but have 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.

<o:p> 

 

 

 

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
Nishith Pathak is an avid reader,Prolific writer, Speaker for Microsoft India,Published Author of APress and a Microsoft Purist.He is MVP, MCPD, MCTS MCSD.Net,MCAD.Net(EA),MCSD. His proficiency lies in exploring Microsoft technology and to share them with other peers. He is a contributing author and an avid technical reviewer for multiple electronic and print publications. He has recently co-authored a book on WCF called Pro WCF: Microsoft Practical SOA Implementation for APress Inc, USA. Over the years, he has also been involved in providing consultancy and training services to corporations. He has been awarded with Microsoft Most Valuable Professional (MVP).Working since beta version of .Net makes his competecy in .Net. He can be contacted at NisPathak@Hotmail.com or at his blog http://DotNetPathak.Blogspot.com. Currently he is focused on key areas of the Microsoft platform, specifically Distributed Computing, service orientation and exploring VISTA and help companies architecting solutions based on Service Oriented Architecture.

Comments and Discussions

 
GeneralMy vote of 1 Pin
paulsasik23-Aug-10 6:40
professionalpaulsasik23-Aug-10 6:40 
GeneralPlease credit Bill Venners' JavaWorld article "Designing with Exceptions" for some of this content Pin
m0w11-Aug-10 22:40
m0w11-Aug-10 22:40 
General&quot;His proficiency lies in exploring Microsoft technology and to share them with other peers&quot; Pin
Christian Graus26-Oct-04 14:34
protectorChristian Graus26-Oct-04 14:34 
GeneralOnce again, another crap "article" Pin
Jim Crafton26-Oct-04 13:41
Jim Crafton26-Oct-04 13:41 
GeneralTHIS IS NOT A F*CKING ARTICLE Pin
Anonymous26-Oct-04 10:11
Anonymous26-Oct-04 10:11 
GeneralRe: THIS IS NOT A F*CKING ARTICLE Pin
Arch4ngel26-Oct-04 11:27
Arch4ngel26-Oct-04 11:27 
GeneralRe: THIS IS NOT A F*CKING ARTICLE Pin
Anonymous31-Oct-04 8:42
Anonymous31-Oct-04 8:42 
GeneralI miss something Pin
DavidNohejl26-Oct-04 4:04
DavidNohejl26-Oct-04 4:04 
GeneralRe: I miss something Pin
Nishith Pathak27-Oct-04 22:25
Nishith Pathak27-Oct-04 22:25 
GeneralRe: I miss something Pin
DavidNohejl28-Oct-04 2:31
DavidNohejl28-Oct-04 2:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.