C++ Exception create custom exception classes

Description

C++ Exception create custom exception classes

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

class CurveBall: public std::exception{
  public:/*from  w w  w  . j av a2  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";
}
// 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;
  }
}



PreviousNext

Related