It is possible that a program can generate more than one type of exceptions. In such cases, we can have more than one catch statement with a single try block.
try
{
// try block
}
catch(datatype_1 arg)
{
// catch block 1
}
catch(datatype_2 arg)
{
// catch block 2
}
……
……
catch(datatype_n arg)
{
// catch block n
}
It is possible that arguments of several catch statements match the type of an exception, In such cases, The first handler that matches the exception type is executed. The type of argument inside the parenthesis of catch block indicates the type of exception that catch block handles an argument is an optional parameter name.
Program for multiple catch block:
#include<iostream>
using namespace std;
void testcase(int x)
{
try
{
if(x==0)
{
//throwing an int type of exception.
throw x;
}
else if(x==1)
{
// throwing a char type of exception.
throw 'x';
}
else if(x==-1)
{
// throwing a double type of exception.
throw 1.0;
}
}
catch(int i)
{
cout<<"Integer type of exception caught in the program code\n";
cout<<"End of multiple try – catch block.\n";
}
catch(char i)
{
cout<<"Character type of exception caught in the program code\n";
cout<<"End of multiple try – catch block.\n";
}
catch(double i)
{
cout<<"Double type of exception caught\n";
cout<<"End of multiple try – catch block.\n";
}
}
int main()
{
int a;
cout<<"Enter any number\n";
cin>>a;
testcase(a);
}
Output 1
Enter a number
1
Character type of exception caught in the program code
End of multiple try-catch block.
Output 2
Enter a number
0
Integer type of exception caught in the program code
End of multiple try-catch block.
Output 3
Enter a number
-1
Double type of exception caught in the program code
End of multiple try-catch block.
Output 4
Enter a number
2
Post A Comment:
0 comments: