home *** CD-ROM | disk | FTP | other *** search
/ Microsoftware Monthly 19…2 Programming Power Tools / MASO9512.ISO / cpptutor / cpptutor.arj / EXAMPLES / EX1609.CPP < prev    next >
Encoding:
C/C++ Source or Header  |  1993-11-24  |  2.1 KB  |  94 lines

  1. // \EXAMPLES\EX1609.CPP
  2.  
  3. //----------------------------------------------------------
  4. //  Exception handling is supported only by
  5. //                            the IBM C Set++ Compiler
  6. //  This example does not work in Borland Turbo C++
  7. //                          or in Microsoft Visual C++
  8. //----------------------------------------------------------
  9. //  To run this program on an OS/2 machine:
  10. //                      move to an OS/2 window
  11. //              [type]  cd:\EXAMPLES\EX1609I
  12. //                      where cd: is the drive of the CD-ROM
  13. //----------------------------------------------------------
  14.  
  15. #include <iostream.h>
  16. #include <terminat.h>
  17. #include <unexpect.h>
  18.  
  19. //
  20. // This is example illustrates set_terminate
  21. //
  22.  
  23. typedef void(*PFV)();
  24. PFV pfvOldTerm;
  25.  
  26.  
  27. //
  28. // FUNCTION: divide(...) divides first parameter by the second
  29. // PARAMETERS: long x dividend
  30. //             long y divisor
  31. // RETURN VALUE: x divided by y
  32. //
  33. long divide(long x, long y)
  34. {
  35.    if (y==0)
  36.    {
  37.       cout << "Divide by zero error, throwing exception."
  38.            << endl;
  39.       throw y;     // can't divide by zero so throw an exception
  40.    }
  41.    return x/y;     // return the quotient
  42. }
  43.  
  44.  
  45. //
  46. // This fucntion is used to throw an exception
  47. //
  48. void Process()
  49. {
  50.    try
  51.    {
  52.       cout << "Forcing a divide by zero error." << endl;
  53.       long z = divide( 1, 0);
  54.    }
  55.    catch( char)
  56.    {
  57.       cout << "This line should not be printed." << endl;
  58.    }
  59. }
  60.  
  61. //
  62. // This is the new terminate function
  63. //
  64. void myTerminate()
  65. {
  66.    // Reset terminate function
  67.    set_terminate( (PFV)pfvOldTerm);
  68.  
  69.    cout << "The terminate function has been reset"
  70.         << " to the previous state."
  71.         << endl;
  72.  
  73.    cout << "Calling Process() from "
  74.         << "the myTerminate()." << endl;
  75.    Process();
  76. }
  77.  
  78.  
  79. main()
  80. {
  81.    // set new terminate function
  82.    // store old terminate function
  83.    pfvOldTerm = set_terminate( (PFV)myTerminate);
  84.  
  85.    cout << "Setting the terminate function to myTerminate()."
  86.         << endl;
  87.  
  88.    // Insert code here to free up resources
  89.  
  90.    cout << "Calling Process()." << endl;
  91.  
  92.    Process();
  93. }
  94.