Friday, October 1, 2010

Exception Handling

What is an 'Exception' ?

'Exception' is an error situation that a program may encounter during runtime. For example, your program may be trying to write into a file, but your hard disk may be full. Or, the program may be trying to update a record in database, but that record may be already deleted. Such errors may happen any time and unless you handle such situation properly, your application may have un predictable behavior.

What is 'Exception Handling'?

An exception can occur anytime during the execution of an application. Your application must be prepared to face such situations. An application will crash if an exception occurs and it is not handled. "An exception handler is a piece of code which will be called when an exception occurs."

.NET Framework provides several classes to work with exceptions. The keywords try, catch are used to handle exceptions in .NET. You have to put the code (that can cause an exception) in a try block. If an exception occurs at any line of code inside a try block, the control of execution will be transfered to the code inside the catch block.

Syntax :

try
{
//Code which can cause exception;
}
catch(Exception ex)
{
//Code to handle the exception;
}

'finally' block 

You can optionally use a 'finally' block along with the try-catch. The 'finally' block is guaranteed to be executed even if there is an exception.

try
{
//Statements;
}
catch(Exception ex)
{
//Statements;
}

finally
{
//Statements;
}

Why should we catch exceptions ?

If an exception is not 'handled' in code, the application will crash and user will see an ugly message. Instead, you can catch the exception, log the errors and show a friendly message to the user.


No comments:

Post a Comment