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

  1. // \EXAMPLES\EX1606.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\EX1606I
  12. //                      where cd: is the drive of the CD-ROM
  13. //----------------------------------------------------------
  14.  
  15. #include <iostream.h>
  16. #include <string.h>
  17.  
  18. //
  19. // This is example shows how define an exception
  20. //
  21.  
  22. typedef char String32[33];  // Used as a generic string
  23.  
  24. //
  25. // Exception
  26. //
  27. class MathExcept {
  28.    String32 sName;
  29. public:
  30.    MathExcept() { strcpy( (char *)sName, "Math Exception"); }
  31.  
  32.    char*
  33.    Name() { return (char *)sName; }
  34. };
  35.  
  36.  
  37. //
  38. // divide: returns x divided by y
  39. //         throws an object of class Exception on error
  40. //
  41. long divide( long x, long y)
  42. {
  43.    if (y==0)
  44.    {
  45.       throw ( MathExcept());
  46.    }
  47.    return ( x/y);
  48. }
  49.  
  50. //
  51. // main calls divide and catches exceptions of class exception
  52. //
  53. main()
  54. {
  55.    try
  56.    {
  57.       long z = divide( 1, 0);
  58.       cout  << "1 divided by 0 is " << z << endl;
  59.    }
  60.    catch( MathExcept except)
  61.    {
  62.       cout << "Exception handler: catch( MathExcept except)"
  63.            << endl
  64.            << "I caught a " << except.Name()
  65.            << " exception.";
  66.    }
  67. }
  68.