Handling Exceptions

Handling Exceptions

The first line of protection in an application is to check for potential error conditions before performing an operation.

For example, a program can explicitly check whether the divisor is 0 before performing a calculation or whether a file exists before attempting to open it:

If (divisor! =0)
{
//it is safe to divide some number by divisor.
}

If (System.IO.File.Exists (“myfile.txt”))
{
//You can now open the myfile.txt file.
//However, you should still use exception handling because a variety of
//problems can intervene (insufficient rights, hardware failure, etc)
}

Even if you perform this basic level of “quality assurance”, your application is still unsafe. For example , you have no way to protect against all the possible file access problems that occur, including hardware failures or network problems that could arise automatically in the middle of an operation.

In some cases, it may not be practical to perform the full range of protection checks, because they may impose a noticeable performance drag on your application. For all these reasons, you need a way to detect and deal with errors when they occur.

The solution is structured exception handling. To use structured exception handling, you wrap potentially problematic code in the special block structure shown in the below code:

Try
{
//Risky code goes here (opening a file, connecting to a database, and so on)
}
Catch
{
//An error has been detected. You can deal with it here.
}
Finally
{
//Time to clean up, regardless of whether or not there was an error.
}

The Try statement allows error handling. Any exception that occurs in the following lines can be “caught “automatically.
The code in the catch block will be executed when an “error is detected”. And either way, whether a bug occurs or not.
The finally block of the code will be executed last .This allows you to perform some basic cleanup, such as closing database connection. The finally code is important because it will execute even if an error has occurred that will prevent the program from continuing.

The act of catching an exception neutralizes it. If all you want to do is render a specific error harmless, you do not even need to add any code in the catch block of your error handler. Usually, this portion of the code will be used to report the error to the user or log it for future reference.