Loading....
Coupon Accepted Successfully!

 

Controlling Uncaught Exceptions

C++ has the following functions, and these can be used to control uncaught exceptions.

terminate(): In case the exception handler is not defined when an exception is thrown, in such a case, the terminate() function is invoked. Implicitly, the abort() function is invoked.

19.8 Write a program caught uncaught exceptions.

#include<iostream.h>

class one {};

class two {};

void main()

{

try

{

cout<<“An Uncaught exception\n”;

throw two();

}

catch (one)

{

cout<<“Exception for one”;

}

}

Explanation: In the above program, an exception is thrown for class two using the statement throw two(). The catch block is defined to handle the exception for class one, and the catch block contains an argument of class one type. When an exception is thrown, it does not find a match; hence, the program is terminated. For termination, the abort() function is called implicitly by the compiler.

set_terminate()

The set terminate() function is used to transfer the control to the specified error-handling function. The set_terminate() function requires only one argument, which is nothing but a function name where control is transferred. It returns nothing. When no function is specified, the program is terminated by an implicit call to abort() function.

19.9 Write a program to demonstrate the use of set_terminate() function.

#include<iostream.h>

#include<except.h>

class one {};

class two {};

void skip()

{

cout<<“\n function skip() is invoked”;

}

void main()

{

set_terminate(skip);

try

{

cout<<“\n Throwing exception:”;

throw (two);

}

catch (one)

{

cout<<“\n An exception of one is caught”;

}

}

// At this point function skip is invoked

OUTPUT

Throwing exception

function skip() is invoked

Explanation: This program is similar to the previous one. The only difference is that in the previous program the compiler does not found a matching catch statement for the exception thrown by the throw statement. The program is terminated. In this program, at the beginning, a user-defined function skip() is defined. The skip() function is associated with the set_terminate() function. When a compiler does not found a matching exception instead of terminating a program, it invokes the function associated with the set_terminate() function. Here, the exception is thrown for an object of class two. The catch statement holds an object of class one. Hence, the thrown exception object does not match the catch object. Due to this mismatch, the function skip() is invoked to handle such an uncertain situation.





Test Your Skills Now!
Take a Quiz now
Reviewer Name