Loading....
Coupon Accepted Successfully!

 

Multiple Catch Statements

We can also define multiple catch blocks; in the try block, such programs also contain multiple throw statements based on certain conditions. The format of multiple catch statements is as follows:

As soon as an exception is thrown, the compiler searches for an appropriate matching catch block. The matching catch block is executed, and control passes to the successive statement after the last catch block. In case no match is found, the program is terminated. In a multiplecatch statement, if objects of many catch statements are similar to the type of an exception, in such a situation, the first catch block that matches is executed.

19.3 Write a program to throw multiple exceptions and define multiple catch statement.

#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(char g)

{

cout<<“Caught a positive value \n”;

}

catch (int j)

{

cout<<“caught an null value \n”;

}

catch (double f)

{

cout<<“Caught a Negative value \n”;

}

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

}

int main()

{

cout<<“Demo of Multiple catches\n”;

num(0);

num(5);

num(-1);

return 0;

}

OUTPUT

Demo of Multiple catches

caught an null value

*** try catch ***

Caught a positive value

*** try catch ***

Caught a Negative value

*** try catch ***

Explanation: In the above program, the function num() contains the try block with multiple catch blocks. In the function main(), the user-defined function num() is invoked with one argument. The if statement within the try block checks the number to see whether it is positive, negative, or zero. According to this, an exception is thrown, and the respective catch block is executed. Here, in the throw statement, objects of different data types such as int, char, and double are used to avoid ambiguity.





Test Your Skills Now!
Take a Quiz now
Reviewer Name