home *** CD-ROM | disk | FTP | other *** search
/ Mastering Microsoft Visual C++ 4 (2nd Edition) / VisualC4.ISO / cpp / extrans.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1994-10-11  |  1.6 KB  |  70 lines

  1. // ExTrans.cpp: Example program demonstrating an exception translator function
  2. //              for translating a Win32 exception to a C++ exception
  3.  
  4. #include <windows.h>
  5. #include <iostream.h>
  6. #include <eh.h>
  7.  
  8. class CSExcept
  9. {
  10. public:
  11.    CSExcept (unsigned int ExCode)
  12.       {
  13.       m_ExCode = ExCode;
  14.       }
  15.    unsigned int GetExCode () 
  16.       {
  17.       return m_ExCode;
  18.       }
  19.  
  20. private:
  21.    unsigned int m_ExCode;
  22. };
  23.  
  24. void SETranslate (unsigned int ExCode, _EXCEPTION_POINTERS *PtrExPtrs)
  25.    {
  26.    throw CSExcept (ExCode);
  27.    }
  28.  
  29. void main ()
  30.    {
  31.    char Ch;
  32.  
  33.    _set_se_translator (SETranslate);
  34.  
  35.    try
  36.       {
  37.       // ...
  38.       cout << "generate 'integer divide by zero' exception? (y/n): "; cin >> Ch;
  39.       if (Ch == 'y' || Ch == 'Y')
  40.          {
  41.          int I = 0;
  42.          int J = 5 / I;
  43.          }
  44.       cout << "generate 'access violation' exception? (y/n): "; cin >> Ch;
  45.       if (Ch == 'y' || Ch == 'Y')
  46.          {
  47.          *((char *)0) = 'x';
  48.          }
  49.       // other statements which may cause other exceptions...
  50.       }
  51.    catch (CSExcept SExcept)
  52.       {
  53.       switch (SExcept.GetExCode ())
  54.          {
  55.          case EXCEPTION_INT_DIVIDE_BY_ZERO:
  56.             cout << "'integer divide by zero' exception occurred" << '\n';
  57.             break;
  58.  
  59.          case EXCEPTION_ACCESS_VIOLATION:
  60.             cout << "'access violation' exception occurred" << '\n';
  61.             break;
  62.  
  63.          default:
  64.             cout << "unknown exception occurred" << '\n';
  65.             throw;
  66.             break;
  67.          }                                        
  68.       }
  69.    }
  70.