Implementing a terminate handler - C++ Class

C++ examples for Class:Exception Class

Description

Implementing a terminate handler

Demo Code

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <exception>

class CurveBall : public std::exception
{
public://w  w w. j av a 2 s . com
  const char* what() const;
};

class TooManyExceptions : public std::exception
{
public:
  const char* what() const;
};

const char* CurveBall::what() const
{
  return "CurveBall exception";
}

const char* TooManyExceptions::what() const
{
  return "TooManyExceptions exception";
}
// Terminate handler
void myHandler()
{
  std::cout << "My termination handler called." << std::endl;
  exit(1);
}

// Function to generate a random integer 0 to count-1
int random(int count)
{
  return static_cast<int>((count*static_cast<unsigned long>(rand())) / (RAND_MAX + 1UL));
}

// Throw a CurveBall exception 25% of the time
void sometimes()
{
  CurveBall e;
  if (random(20)<5)
    throw e;
}

int main(){
  std::srand((unsigned)std::time(0));            // Seed random number generator
  int number {1000};                          // Number of loop iterations
  int exceptionCount {};                      // Count of exceptions thrown
  TooManyExceptions eTooMany;                    // Exception object

  set_terminate(myHandler);                      // Install our own handler

  for (int i {}; i < number; ++i){
      try
      {
        sometimes();
      }
      catch (CurveBall& e)
      {
        std::cout << e.what() << std::endl;
        if (++exceptionCount > 10)
          throw eTooMany;
      }
  }
}

Result


Related Tutorials