Loading....
Coupon Accepted Successfully!

 

Re-Throwing Exception

It is also possible to again pass the exception received to another exception handler; that is, an exception is thrown from the catch block; this is known as the re-throwing exception. The following statement accomplishes this:

throw;

The above throw statement is used without any argument. This statement throws the exception caught to the next try catch statement. The following program illustrates this:

19.5 Write a program to re-throw an exception.

#include<iostream.h>

void sub( int j, int k)

{

cout<<“inside function sub()\n”;

try

{

if (j==0)

throw j;

else

cout<<“Subtraction=”<<j-k<<“\n”;

}

catch (int)

{

cout<<“Caught Null value \n”;

throw;

}

cout<<“** End of sub() ***\n\n”;

}

int main()

{

cout<<“\n inside function main()\n”;

try

sub (8,5);

sub (0,8);

}

catch (int)

{

cout<<“caught null inside main() \n”;

}

cout<<“end of function main() \n”;

return 0;

}

OUTPUT

inside function main()

inside function sub()

Subtraction = 3

** End of sub() ***

inside function sub()

Caught Null value

caught null inside main()

end of function main()

Explanation: In the above program, two try blocks are defined. One is defined in the function sub(), and the other is defined in the function main(). The sub() function has two integer arguments. When the sub() function is invoked, two integer values are sent to this function. Theif statement in the try block of the sub() function checks whether the value of the first variable, that is, j is zero or non-zero. If it is non-zero, subtraction is carried out; otherwise, the throw statement throws an exception. The catch block inside the function sub() collects this exception and again throws the exception using the throw statement. Here, the throw statement is used without any argument. The catch block of the main function catches the re-thrown exception.





Test Your Skills Now!
Take a Quiz now
Reviewer Name