Example of Using the Exception Handling Functions


/************************************************************************
*

The following example shows the flow of control and special functions used in exception handling:

                                                                        *
************************************************************************/

#include <terminat.h>
#include <unexpect.h>
#include <iostream.h>
class X { /* ... */ };
class Y { /* ... */ };
class A { /* ... */ };
// pfv type is pointer to function returning void
typedef void (*pfv)();
void my_terminate()
{      cout << "Call to my terminate" << endl; }
void my_unexpected()
{      cout << "Call to my unexpected" << endl; }
void f() throw(X,Y)      // f() is permitted to throw objects of class
                         // types X and Y only
{
      A aobj;
      throw(aobj); // error, f() throws a class A object
}
main()
{
      pfv old_term = set_terminate(my_terminate);
      pfv old_unex = set_unexpected(my_unexpected);
      try{ f(); }
      catch(X)       { /* ... */ }
      catch(Y)       { /* ... */ }
      catch (...)    { /* ... */ }

      set_unexpected(old_unex);
      try { f();}
      catch(X)       { /* ... */ }
      catch(Y)       { /* ... */ }
      catch (...)    { /* ... */ }
}

/************************************************************************
*

At run time, this program behaves as follows:

  1. call to set_terminate() assigns to old_term the address of the function last passed to set_terminate() when set� 95;terminate() was previously called.
  2. call to set_unexpected() assigns to old_unex the address of the function last passed to set_unexpected() when set& #095;unexpected() was previously called.
  3. a try block, function f() is called. Because f() throws an unexpected exception, a call to unexpected() is made. unexpe cted() in turn calls my_unexpected(), which prints a message to standard output and returns.
  4. second call to set_unexpected() replaces the user-defined function my_unexpected() with the saved pointer to the origin al function (terminate()) called by unexpected().
  5. a second try block, function f() is called once more. Because f() throws an unexpected exception, a call to unexpected( ) is again made. unexpected() automatically calls terminate(), which calls the function my_terminate().
  6. displays a message. It returns, and the system calls abort(), which terminates the program.

At run time, the following information is displayed, and the program ends:

Call to my_unexpected
Call to my_terminate

Note: The catch blocks following the try block are not entered , because the exception was handled by my_unexpected() as an unexpected throw, not as a valid exception.

                                                                        *
************************************************************************/