How to use Exception Handling?

 Posted by Bharathi Cherukuri on 2/2/2012 | Category: ASP.NET Interview questions | Views: 3044 | Points: 40
Answer:

What is Exception?
An Exception is an unexpected error or problem.
What is Exception Handling?
It is a method to handle the error and solution to recover from it which makes the program to work smoothly.

What is try Block?
The try block consists of the code that might generate an error.
This try block must be associated with one or more catch blocks or by finally block.
The try block may not have a catch block associated with it every time but in this case,it must have a finally block associated with it instead of catch block.

Example:

Format1


try
{
//Code that might generate error
}
catch(Exception error)
{
}

Format2

try
{
//Code that might generate error
}
catch(ExceptionA error)
{
}
catch(ExceptionB error)
{
}

Format3

try
{
//Code that might generate error
}
finally
{
}


What is catch Block?
catch block is used to recover from error generated in the try block.
In case of multiple catch blocks,only the first matching catch block is excecuted.
you need to arrange the multiple catch blocks from specific exception type to more generic type.
If none of the matching catch blocks are able to handle the exception, the default behaviour of web page is to terminate the processing of the web page.

Example:

Format1


try
{
//Code that might generate error
}
catch(Exception error)
{
//Code that handle errors occurred in try block
}

Format2:

try
{
//Code that might generate error
}
catch(DivideByZeroException error)
{
//Code that handle errors occurred in try block
//It is the most specific error we are trying to catch
}
catch(Exception error)
{
//Code that handle errors occurred in try block
//It is not specific error we are catching
}
catch
{
//Code that handle errors occurred in try block
//It is the least specific error in hierarchy
}


What is finally Block?
The finally block contains the code that executes,whether an exception occurs or not.
The finally block is used to write code to close files,database connections,etc.
Only one finally block is associated with each try block.
finally block must appear only after the catch block.
If there are any control statements such as goto,break or continue in either try or catch block,the transfer happens only after the code in the finally block is excecuted.
If the control statements are used in finally block,there occurs a compile time error.

Example:

Format1


try
{
//Code that might generate error
}
catch(Exception error)
{
//Code that handle errors occurred in try block
}
finally
{
//Code to dispose all allocated resources
}

Format2

try
{
//Code that might generate error
}
finally
{
//Code to dispose all allocated resources
}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response