Listing 2: The same program as Listing 1 with functions inserted to simulate errors

int main(int argc, char **argv)
{
   bool           bOK = true;  // keep going if true
   int            nResult;
   CSampleObject *pObject;
   char          *pArray;
   SimErrCustomInit(SIMERR_TIME_SEED, SIMERR_SYSTEMATIC);
 
   // Instantiate object with C++ allocation
   pObject = new CSampleObject;
   pObject = SimErrNew(SIMLINE, pObject, SIMERR_FOREVER, .4);
   if (pObject==0)
   {
      printf("C++ allocation error.\n");
      bOK = false;
   }
   else
   {
      delete pObject;
   }
   // Allocate char array with malloc
   if (bOK)
   {
      pArray = (char *) malloc(100);
      pArray = SimErrMalloc(SIMLINE, pArray);
      if (pArray==0)
      {
         printf("C allocation error.\n");
         bOK = false;
      }
      else
      {
         delete pArray;
      }
   }
   try
   {
      if (bOK)
      {  // Adjust real-time device
         //   note: AdjustValve can throw a CDeviceException
         bOK = AdjustValve();                  
         SimErrException(SIMLINE, SIMERR_DEVICE_EXCEPTION,
            4, 0.33);
         bOK = SimErrZero(SIMLINE, bOK, SIMERR_FOREVER, 0.2);            
         if (!bOK)
         {
            printf("The valve stuck.\n");
         }
      }
      if (bOK)
      {  // Update remote-server database
         //   note: UpdateDatabase can throw a CDatabaseException
         nResult = UpdateDatabase();          
         SimErrException(SIMLINE, SIMERR_DATABASE_EXCEPTION); 
         nResult = SimErrResult(SIMLINE, nResult, DATABASE_ERROR);
         if (nResult == DATABASE_ERROR)        
         {
            printf("Database update failed.\n");
            bOK = false;
         }
      }
   }
   catch(CDeviceException *pDeviceException)
   {
      printf("Unrecoverable device error.\n");
      delete pDeviceException;
      bOK = false;
   }
   catch(CDatabaseException *pDBException)
   {
      printf("Unrecoverable database error.\n");
      delete pDBException;
      bOK = false;
   }
   catch(...)
   {
      printf("Unknown exception.\n");
      bOK = false;
   }
   nResult = (bOK) ? 0 : -1;
   printf("Sample program exiting with return code = %d.\n",
          nResult);
   SimErrExit(true);
   return nResult;
}
//End of File