Loading....
Coupon Accepted Successfully!

 

Catching Multiple Exceptions

It is also possible to define a single or default catch block from one or more exceptions of different types. In such a situation, a single catch block is used to catch the exceptions thrown by the multiple throw statements.

19.4 Write a program to catch multiple exceptions.

#include<iostream.h>

void num (int k)

{

try

{

if (k==0) throw k;

else

if (k>0) throw ‘P’;

else

if (k<0) throw .0;

cout<<“*** try block ***\n”;

}

catch

{

cout<<“\n Caught an exception\n”;

}

}

int main()

{

num(0);

num(5);

num(-1);

return 0;

}

OUTPUT

Caught an exception

Caught an exception

Caught an exception

Explanation: The above program is similar to the previous one. Here, only one difference is observed and that is, instead of multiple catch blocks, a single catch block is defined. For all the exceptions thrown, the same catch block is executed. It is a generic type of catch block. The statement catch catches all the exceptions thrown.





Test Your Skills Now!
Take a Quiz now
Reviewer Name