Exception handling ( try,catch and throw) in C++

Exception handling :- We know that it is very rare that a program works correctly first time. It might have bugs. The two most common types of bugs are logical 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 programming language. We can detect these errors by using exhaustive debugging and testing procedures. 
    We often come across some peculiar problems other than logic or syntactic errors. They are known as exception. 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 money or disk space. When a program encounters an exceptional condition, it is important that it is identified and dealt with effectively. ANSI C++ provides built-in language features to detect and handle exception which are basically run time errors.
       Exception handling was not part of the original C++ language. It is a new feature added to ANSI C++. Today, almost all compilers support this feature. C++ exception handling provides a type safe, integrated approach for coping with the unusual predictable problems that arise while executing a program.

Exception handling mechanism:- The purpose of exception handling mechanism is to provide means to detect and report an “exceptional circumstances” 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 exception).
3. Receive the error information (catch the exception).
4. Take corrective actions  (handle the exception).

C++ exception handling mechanism is basically built upon three keywords – 
1. Try keyword    2. Throw keyword    3. Catch keyword

1. Try keyword :- The keyword try is used to preface a block of statement. This block is known as try block. When an exception is detected,  it is thrown using a throw statement in the try block.

2. Throw keyword :- We use throw keyword for throwing exception which occurred in try block. Thrown exception is send to catch block. Here we take appropriate action for it.

3. Catch keyword :- We take appropriate action in catch block for exception which was thrown from try block i.e. exception was handled by catch block. 

Example:-
C++ program for exception handling try, catch, throw.
#include<iostream.h>
#include<conio.h>
void main(){
int x,a,b;
cout<<"Enter value of a & b"<<endl;
cin>>a>>b;
x=a-b;
try{
if (x!=0) cout<<"Answer is="<<a/x<<endl;
else throw(x);
}
catch(int e){
cout<<"Exception Caught ="<<e<<endl<<"Divisor must be a non-zero value"<<endl;
}
getch();
}

No comments:

Post a Comment