Specifying an exception :- In C++ language, it is possible that at the time of specifying of function it was bounded for throwing some special exceptions. It is possible by function with throw keyword (throw last clause).
Syntax :- type function_name (arg list) throw (type list){
statements;
..............
.............
..............
}
Here type od thrown exception by type list is shown. If thrown type exceptions are different then program is abnormally terminated.
Example:-
C++ program for specifying an exception.
#include<iostream.h>
#include<conio.h>
void test(int x) throw(int,char,double){
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 specifying exception handling..."<<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();
}
Syntax :- type function_name (arg list) throw (type list){
statements;
..............
.............
..............
}
Here type od thrown exception by type list is shown. If thrown type exceptions are different then program is abnormally terminated.
Example:-
C++ program for specifying an exception.
#include<iostream.h>
#include<conio.h>
void test(int x) throw(int,char,double){
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 specifying exception handling..."<<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