C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Exception Handling: Exceptions Let You Handle Errors Gracefully


Posted Date: 02 Apr 2004    Resource Type: Articles    Category: .NET Framework
Author: ANITA MARY JOSEPHMember Level: Gold    
Rating: 1 out of 5Points: 10



Exception Handling Fundamentals

C# exception handling is managed by four keywords:

try

catch

throw

finally

Within the try Block you have the Program statements that you want to monitor for exceptions. If an exception occurs within the try block, it is thrown. Your code can catch this exception using catch and handle it in an appropriate manner. System-generated exceptions are automatically thrown by the C# runtime system. To manually throw an exception use the key word throw. Any code that absolutely must be executed upon exiting from a try block is put in a finally block.

Using Multiple catch Statements
You can associate more than one catch statement with a try, but each catch must catch a different type of exception.

Catching All Exceptions
At times you will want to catch all exceptions, no matter the type. To do this just use a catch statement that specifies no parameter.

Nesting Try Blocks
One try block can be nested with another. An exception generated within the inner try block that is not caught by a catch associated with that try is propagated to the outer try block.

Rethrowing an Exception
An exception caught by one catch statement can be rethrown so that it can be caught by an outer catch. To rethrow an exception all you have to do is specify throw without specifying an exception. Remember that when you rethrow an exception, it will not be caught by the same catch statement whereas It will propagate to the next catch statement.

General-Form

try

{

// block of code to monitor for errors

throw new DivideByZeroException(); //manually throws the exception;

}

catch( ExcepType1 exObject )

{

//handler for ExcepType1

}

catch( ExcepType2 exObject )

{

//handler for ExcepType2

}

finally

{

//finally code

}


Commonly Used Exceptions

OverflowException : An arithmetic overflow occurred.
NullReferenceException : An attempt was made to operate on a null reference-
that is, a reference that does not refer to an object..
StackOverflowException : The stack was overrun.

ArrayTypeMismatchException : Type of value being stored is incompatible with the type of the
array.
DivideByZeroException : Division by zero attempted.
IndexOutOfRangeException : Array index is out of bounds.
InvalidCastException : A runtime cast is invalid.
OutOfMemoryException : A call to new fails because insufficient free memory
exists.

Using checked and unchecked
C# allows you to specify whether your code will raise an exception when overflow occurs by using the keywords checked and unchecked. To specify that an expression be checked for overflow use checked. To specify that overflow be ignored, use unchecked. In this case the result is truncated to fit into the target type of the expression.

The checked keyword has two general forms. One checks a specific expression and is called the operator form of checked. The other checks a block of statements-

Checked(expr)

Checked

{

//statements to be checked.

}

Similarly unchecked follows the two formats.

Catching A Derived Class Exception
Thw way you order catch statements when trying to catch exception types that involve base and derived classes is very Important, because a catch clause for a base class will also match any of its derived classes.
If you want to catch exceptions of both a base class type and a derived class type, all you have to do is put the derived class first in the catch sequence. If you don’t then the base class catch will also catch all derived classes

using System;

//Create an exception.

class ExceptionA : ApplicationException

{

public ExceptionA() : base() { }

public ExceptionA(string str) : base(str) { }

public override string ToString()

{

return Message;

}

}

//Create an exception derived from ExceptA

class ExceptionB : ExceptionA

{

public ExceptionB() : base()

{

}

public ExceptionB( string str ) : base( str )

{

}

public override string ToString()

{

return Message;

}

}

class CorrectOrderMatters

{

public static void Main()

{

for( int x = 0; x < 3; x++ )

{

try

{

if ( x == 0 ) throw new ExceptionA("caught an ExceptionA exception");

else if( x == 1 ) throw new ExceptionB("Caught an ExceptionB exception");

else throw new Exception();

}

catch( ExceptionB exc)

{

//catch the exception

Console.WriteLine(exc);

}

catch( ExceptionA exc)

{

//catch the exception

Console.WriteLine(exc);

}

catch( Exception exc)

{

//catch the exception

Console.WriteLine(exc);

}

}
Console.ReadLine();
}


}

Notice the order of the catch statements. This is the only order in which they can occur.
Since ExceptionB is derived from ExceptionA, the catch statement for ExceptionB must be before the one for ExceptionA. Similarly, the catch for Exception (which is the base class for all exceptions)must appear last. Try rearranging the catch statements and you can prove this point to your self - It will result in a compile-time error.




Responses

Author: Manoj Oommen    19 Apr 2004Member Level: Bronze   Points : 0
good article., but would like to know how exception and stack ate connected.


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Tips in VB.NET - Tip #8
Previous Resource: Attributes : The Additional Information that is associated with a class, structure, method...
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use