Exception Handling In C++ With Example

Explain Exception Handling in C++ with Example and Program


Exception Handling

•    The two most common types of bugs are logic errors and syntactic errors. The logic errors occur due to poor understanding of the problem and solution procedure. The syntactic errors arise due to poor understanding of the language itself. We can detect these errors by using exhaustive debugging and testing procedures .

•    WE often come across some peculiar problems other than logic or syntax errors. They are known as exceptions. Exceptions are run time anomalies or unusual conditions that a program may encounter while executing. Anomalies might include conditions such as division by zero, access to an array outside of its bounds, or running out of memory or disk space

Exceptions are of two kinds, namely, synchronous exceptions and asynchronous exceptions. Errors such as “out-of-range index” and “over-flow” belong to the synchronous type exceptions. The errors that are caused by events beyond the control  of the program (such as keyboard interrupts) are called asynchronous exceptions. The exception handling mechanism in C++ is designed to handle only synchronous exceptions
•    The purpose of the exception handling mechanism is to provide means to detect and report an “exceptional circumstance” so that appropriate action can be taken. The mechanism suggests a separate error handling code that performs the following tasks.

1)Find the problem (Hit the exception)
2)Inform that an error has occurred (Throw the exception)
3)Receive the error information (Catch the exception)
4)Take corrective actions (Handle the exception)

•    The catch block that catches an exception must immediately follow the try block that throws the exception. The general form of these two blocks are as follows:
•         Try
               {
…….
Throw exception ;    //Block if statements which
…………        //detects and throws an exception
………..
}
Catch  (type arg)    //Catches exception
{
……        //Block of statements that
……….        //handles the exception
…….

}




Labels: