Tuesday, December 19, 2006

Exception Handling in C#

Exception class is used to handle errors occurred during execution of code. Following are public members of exception class:

HelpLink : Used to set help link for exception.

InnerException: Gets the exception instance that caused the current exception.

Message: Exception description.

Source: Object that caused exception

StackTrace: Call stack for occurred exception.

TargetSite: Method that throws the exception.

Simple exception handling code block:

try

{

// Code statements.

}

catch(Type x)

{

// handling of the exception

}

finally

{

//cleanup code (if any)

}

Note: Catch block is optional in C#. And Finally block always execute.

Multiple Catch Blocks: (All good Programs must be able to uniformly handle errors that occur during code execution.)

try

{

//Your code goes here

}

catch(DivideByZeroException dz)

{

//Divide by zero exceptions will be handled here.

}

catch(OutOfMemoryException oe)

{

//Out of memory exceptions will be handled here.

}

catch(NullReferenceException ee)

{

//Null refernce exceptions will be handled here.

}

catch(Exception ex)

{

//Unknown exceptions from above 3 types will be handled here.

}

finally

{

//Always executes at the end.

}

Some Other Exception types:

IndexOutOfRangeException (Occures in looping when Index is out of range)

InvalidOperationException (Thrown by methods when in an invalid state.)

ArgumentNullException (Thrown by methods that do not allow an argument to be null.)

ComException (COM components)

InvalidCastException

ArithmeticException

SqlException (For DB related exceptions)

ApplicationException Class:

If you are designing an application that needs to create its own exceptions, derive from the ApplicationException class. ApplicationException extends Exception class.

To know more about structured and ApplicatioException handling goto http://www.devcity.net/Articles/284/1/article.aspx (This is supported by Microsoft)

Best practices to handling exceptions:

URL:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconbestpracticesforhandlingexceptions.asp

No comments:

Visitor Count: