August 07, 2006

Exception Handling C#

Topic:
Exception Handling. Exception are common in programs like dividebyzero, nullreference, tns: timeout

What is exception handling:
Exception handling is structural way of handling the errors and exception.

How to use:
Exception are handled in C# using try, catch, finally optional is throw. The code that can throw exception is inserted in try block

try
{
int var=0;
int var2=10;
var=10/var;
}
Catch(dividebyzeroexception ex)
{
//do appropriate action


var=0;

}
finally
{
//any connection close etc//

file close etc.

}
Catch block handled the exception you can do appropriate action when exception occur.
finally will exceute always whether exception occur or not.
so always place code that must exceute. like connection close;
whether exception occur or not we must close the connection.
possible blocks are:

try{
//code
}

catch{
//code
}
finally{
//c sharp code
}
--------------------
try{
}

catch(OracleException ex)
{
//c# code,
}
catch(NullReferenceException ex)
{
//code: re throw with inner exception or message
throw ex;
}
catch(Exception ex)
{
throw new Exception("sql server insertion error",ex);
}

//Here Exception is catch at last because it is parent class of all the exception classes. so if any child parent relation ship exists between any of the exception, child will be catch above the parent.

Exception: because it is base class of every class. because it will catch all the exception if placed first and code not reachable compiler error will be there.
Example
so if you have Arithmatic Exception and dividebyzero exception place dividebyzero
first then arithmatic exception. coz arithmatic will catch all the error related to mathematic calculations

try and finally can co-exist without catch block but only one finally can be there
try{}
finally{}
//Following is error
try{}
finally{}
{} finally
{}//error

Caution:

finally block will execute in both cases whether exception occurs or not.

and finally always executes.

for example if you put "return;" keyword in the try or catch, it will not create any problem in execution path, and code in finally will execute


You can post comments if any query is there.

2 comments:

Anonymous said...

why is divide by 0 undefined; it is actually infinity

Anonymous said...

hey! whiskypriest what is diffrent b/w undefined and infinity? Infinity is also not defined.