Loading....
Coupon Accepted Successfully!

 

Specifying Exceptions

The specified exceptions are used when we want to bind the function to throw only specified exceptions. Specific exception is thrown using condition statement and list of data items in throw. The format for such exceptions is as given below:

Specifying Exceptions

Data-type fucntion_name (parameter list) throw (data type list)

{

Statement 1;

Statement 2; Function definition

statement 3;

}

The data type list indicates the type of exception that is permitted to be thrown. If we want to deny a function from throwing an exception, declaring the data type list void as per the following statement can do this.

throw(); // void or vacant list

19.6 Write a program to restrict a function to throw only specified type of exceptions.

#include<iostream>

using namespace std;

void check (int k) throw (int,double)

{

if (k==1) throw ‘k’;

else

if (k==2) throw k;

else

if (k==-2) throw 1.0;

cout<<“\n End of function check()”;

}

void main()

{

try {

cout<<“k==1\n”;

check(1);

cout<<“k==2\n”;

check(2);

cout<<“k==-2\n”;

check(-2);

cout<<“k==3\n”;

check(3);

}

catch ( char g)

{

cout<<“Caught a character exception \n”;

}

catch (int j)

{

cout<<“Caught a character exception \n”;

}

catch (double s)

{

cout<<“Caught a double exception \n”;

}

cout<<“\n End of main()”;

}

OUTPUT

k==1

Caught a character exception

End of main() Press any k

Explanation: In the above program, the check() function is defined. It is followed by an exception specifying statement. The if statements check the value of the formal argument. According to the value, an exception is thrown. In function main(), the function check() is invoked with different values. The output of the program is as given above.





Test Your Skills Now!
Take a Quiz now
Reviewer Name