Throwing and catching Exception - C++ Statement

C++ examples for Statement:throw

Description

Throwing and catching Exception

Demo Code

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

class CurveBall: public std::exception
{
public://w w  w .j  a  v a 2  s .c  o  m
  const char* what() const;
};

const char* CurveBall::what() const
{
  return "CurveBall 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

  for (int i {}; i < number; ++i)
  try
  {
    sometimes();
  }
  catch(CurveBall& e)
  {
    exceptionCount++;
  }
  std::cout << "CurveBall exception thrown " << exceptionCount << " times out of " << number << ".\n";
}

Result


Related Tutorials