Multiple catch statement
It is possible that a program segment has more than one condition to throw an exception.
Syntax
try
{
//try block
}
catch(type1 arg)
{
//catch block1
}
catch(type2 arg)
{
//catch block2
}
………
………
catch(typeN arg)
{
//catch blockN
}
when an exception is thrown,the exception handlers are searched in order for an appropriate match.The first handler that yields a match is excuted.After executing the handler,the control goes to the first statement after the last catch block for that try.when no match is found,the program is terminated.
It is possible thar arguments of several catch statements match the type of an exception.In such cases,the first handler that matches the exception type is executed.
Example
#include <iostream.h>
void test(int x)
{
try
{
if(x==1)throw x;
else
if(x==0)throw ‘x’;
else
if(x==-1)throw 1.0;
cout<<”End of try-block \n”;
}
catch(char c)
{
cout<<”Caught a character \n”;
}
catch(int m)
{
cout<<”Caught an integer \n”;
}
catch(double d)
{
cout<<”Caught a double \n”;
}
cout<<”End of try-catch system \n\n”;
}
int main()
{
cout<<”testing Multiple Catches \n”;
cout<<”x ==1 \n”;
test(1);
cout<<”x ==0 \n”;
test(0);
cout<<”x ==-1 \n”;
test(-1);
cout<<”x ==2 \n”;
test(2);
return 0;
} |