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

  1. // \EXAMPLES\EX1611.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\EX1611I
  12. //                      where cd: is the drive of the CD-ROM
  13. //----------------------------------------------------------
  14.  
  15. #include <iostream.h>
  16.  
  17. class MathErr { };   // Used to throw Math related exceptions
  18.  
  19. //
  20. // FUNCTION: divide(...) divides first parameter by second
  21. // PARAMETERS: long x dividend
  22. //             long y divisor
  23. // RETURN VALUE: x divided by y
  24. //
  25. long divide(long x, long y) throw ( long)
  26. {
  27.    if (y==0)
  28.    {
  29.       throw y;  // can't divide by zero so throw an exception
  30.    }
  31.    return x/y;  // return the quotient
  32. }
  33.  
  34.  
  35. //
  36. // FUNCTION: Process does the work
  37. // EXCEPTION SPEC: does not throw any exceptions
  38. //
  39. void Process() throw( MathErr)
  40. {
  41.    long z = divide( 1, 0);   // attempt to divide one by zero
  42. }
  43.  
  44. void main()
  45. {
  46.    try
  47.    {
  48.       cout << "Calling Process()" << endl;
  49.       Process();
  50.    }
  51.    catch(long x)  // unexpected is called instead
  52.    {
  53.       cout << "An unexpected exception was thrown, "
  54.            << "these lines won't be executed.";
  55.    }
  56. }
  57.