Implementation of CurveBall and TooManyExceptions exception classes, Throwing and catching CurveBalls and throwing TooManyExceptions - C++ Class

C++ examples for Class:Exception Class

Description

Implementation of CurveBall and TooManyExceptions exception classes, Throwing and catching CurveBalls and throwing TooManyExceptions

Demo Code

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

class CurveBall: public std::exception{
  public:/*from  w  w w. jav a  2  s  .c om*/
    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";
}
// 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

  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