Related Posts with Thumbnails

Exception classes in .NET

Monday, May 3, 2010

NET Framework provides several classes to work with exceptions. When there is an exception, the .NET framework creates an object of type 'Exception' and 'throws' it. This Exception object contains all information about the 'error'.

If you enclose your code within the try-catch block, you will receive the exception object in the 'catch' block when the exception occurs. You can use this object to retrieve the information regarding the error and take appropriate action.




try
{
// Code which can cause an exception.
}
catch(Exception ex)
{
// Code to handle exception
MessageBox.Show ( ex.Message );
}

Within the catch block, you can use the Exception object to get more information about the error. The exception object exposes a property called 'Message', which gives a description about the error. This may not be a very friendly message for the end user. But you can use it to log the error and show another friendly message to the user.

The System.Exception class

In .NET, all exceptions are derived from the Exception class. The Exception class is defined inside the System namespace.Other derived exception classes are spread across many other namespaces.

Since all other exceptions are derived from the System.Exception class, if you catch System.Exception, that would cover all exceptions derived from System.Exception also. So, the statement catch (Exception) would catch all exceptions of type System.Exception and all derived exceptions. In .NET, all exceptions are derived from System.Exception. So,catch (Exception) will catch all posibble exceptions in your .NET application.

Specify what exception type you want to catch

See the catch block in the above sample code. catch ( Exception ex ) - specifies that we want to catch all exceptions of Type Exception. So, if there is an exception of Type Exception, it will be caught by the catch block.

If you specify an exception Type in the catch statement, it will catch all exceptions of the specified type and all types derived from it.

See the following sample :





try
{
// Code which can cause an exception.
}
catch(System.Web.HttpException ex)
{
// Code to handle exception
MessageBox.Show ( ex.Message );
}

The above example will only catch the exception of type System.Web.HttpException and any other exception derived from it. So, if there is any exception of typeSystem.ArithmeticException, it will not be handled and it may lead to program termination.

Handling specific Exception types

In my previous article, I mentioned few examples from real life - "When you ride a bike, you may wear a helmet. When you go for boating, you might use a life jacket. A car driver might use seat belts while driving at high speed in a high way. What is the purpose ? To handle exceptions (accidents), right ? We do not know when it might happen, so we are prepared to 'handle' such situations any time. "

Yes, a helmet helps a bike rider when he meet with an accident. A life jacket may be helpful in water and a seat belt would help a car driver. But what if some one ride a bike with a helpmet, life jacket and a seat belt ? That may not look good, right ?

Similarly, in Exception handling, you do not need to catch all exceptions. You need to catch only the 'expected' exceptions. Which means,if you are doing an arithmetic calculation, you must handle ArithmeticException and DivideByZeroException. When you are accessing the web from your code, you must handle HttpException.

The bottom line is, depending on the nature of the code, you must handle the appropriate, specific exceptions, instead of catching the father of all exceptions (System.Exception).

Multiple catch blocks

You can have any number of catch blocks for each try block. For example, if you are doing some operation which involve web access and also some arithmetic operations, you can handle both System.Web.HttpException and System.ArithmeticException. See the sample below:




try
{
// Code which can cause a web exception or arithmetic exception.
}
catch(System.Web.HttpException ex)
{
MessageBox.Show ( "A web exception occurred." );
}
catch(System.ArithmeticException ex)
{
MessageBox.Show ( "An arithmetic exception occurred." );
}

Program Flow

When an exception occurs within a try block, the program control will jump to the first catch block and compare if the exception type is same the as the type specified in the catch block. If the type matches, it will execute the catch block. If the types do not match, it will jump to the next catch block and compare. Like this, it will compare against all catch blocks until a match is found. If there is no catch block found which matches the exception type, it will become an unhandled exception and will lead to program termination

Catch derived exceptions first and base exception last

A base exception type will match the derived exceptions also. If there is a catch block with the type 'Exception', it will catch all types of exceptions. So, you have multiple catch blocks, you must specify the derived exception types first and the base types last. See the following code:



try
{
// Code which can cause a web exception or arithmetic exception.
}
catch (System.Exception ex)
{
MessageBox.Show ( "An exception occurred." );
}
catch (System.Web.HttpException ex)
{
MessageBox.Show ( "A web exception occurred." );
}

In the above code, assume there is a web exception occurred. The exception type will be compared against the first catch block. Since the WebException is derived from System.Exception or oneof it's derived classes, the types will match and the first catch block will be executed. So, you might be expecting that the catch (System.Web.HttpException)block will be executed, but it would never get called because of the catch(System.Exception ex) before that.

You must change the above code as shown below :



try
{
// Code which can cause a web exception or arithmetic exception.
}
catch (System.Web.HttpException ex)
{
MessageBox.Show ( "A web exception occurred." );
}
catch(System.Exception ex)
{
MessageBox.Show ( "An exception occurred." );
}

Now, if there is a web exception, it will go to the catch (System.Web.HttpException ex) block. All other exceptions will go to catch (System.Exception ex).

Some commonly used .NET Exception classes

System.ArithmeticException - This is the base class for exceptions that occur during arithmetic operations, such as System.DivideByZeroException and System.OverflowException.

System.ArrayTypeMismatchException - ArrayTypeMismatchException is thrown when a an incompatible object is attpemted to store into an Array.

System.DivideByZeroException - This exception is thrown when an attempt to divide a number by zero.

System.IndexOutOfRangeException - IndexOutOfRangeException is thrown when attempted to access an array using an index that is less than zero or outside the bounds of the array.

System.InvalidCastException - Thrown when an explicit type conversion from a base type or interface to a derived type fails at run time.

System.NullReferenceException - This exception is thrown when an object is accessed but it is null.

System.OutOfMemoryException - OutOfMemoryException is thrown if the 'new' operation (creating new object) fails due to in sufficient memory.

System.OverflowException - OverflowException is thrown when an arithmetic operation overflows.

System.StackOverflowException - StackOverflowException is thrown when the execution stack is exhausted by having too many pending method calls, most probably due to infinite loop.

ArgumentException - The exception that is thrown when one of the arguments provided to a method is not valid.

0 comments:

Post a Comment

Site Rate