Multiple catch statement

Multiple catch statement :- In any program one or more types of unusual conditions are occurred which can throw various types pf exceptions. To handle all this exceptions, two or more catch blocks are used. It is collectively called multiple catch block. The moment when exception throw then it is searched by it’s related blocks exception handler and catch block is executed while best match is found. If argument exists in one or more catch block then first catch is executed. 
Syntax :-  try {
                 statements;
..............
..............
throw exception;
.............
}
                catch (type1 arg){
                statements ;
............
}
         catch (type2 arg){
statements ;
.............
}

Cpp program for multiple catch block in exception handling.
#include<iostream.h>
#include<conio.h>
void test(int x){
try{
if(x==1) throw 5; //int
if(x==0) throw 'e'; //char
if(x==-1) throw 1.0; //double
}
catch(int i){
cout<<"Caught an integer = "<<i<<endl;
}
catch(char c){
cout<<"Caught a character = "<<c<<endl;
}
catch(double d){
cout<<"Caught a double = "<<d<<endl;
}}
void main(){
cout<<"Testing multiple catches..."<<endl;
cout<<"x==1"<<endl;
test(1);
cout<<"x==0"<<endl;
test(0);
cout<<"x==-1"<<endl;
test(-1);
cout<<"x==-2"<<endl;
test(-2);
getch();
}

No comments:

Post a Comment