Throwing mechanism

Throwing mechanism :- If an exception is occurred in any statement pf try block then we throw to detect it for handling. This work is done by throw keyword and this process is called throwing mechanism. Throw statement may be written in following forms- 

Syntax:-
throw(exception);
throw exception;
throw; // used in catch block for re-throw

Example:-

1.) 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();
}

2.) C++ program for exception handling try, catch, throw.
#include<iostream.h>
#include<conio.h>
void divide(int x,int y,int z){
if ((x-y)!=0){
int R=z/(x-y);
cout<<"Result="<<R <<endl;
}
else throw(x-y);
}
void main(){
try{
divide(10,20,40);
divide(10,10,30); //invoke divide
}
catch(int i){
cout<<"Exception Caught x-y="<<i<<endl;
//throw; for rethrow
}
getch();
}

No comments:

Post a Comment