C++ Exception Throwing and catching

Description

C++ Exception Throwing and catching

#include <iostream>

int main(){/*from  w ww . ja  v a  2s . com*/
  for (int i {}; i < 7; ++i){
    try{
      if (i < 3)
        throw i;

      std::cout << " i not thrown - value is " << i << std::endl;

      if (i > 5)
        throw "Here is another!";

      std::cout << " End of the try block." << std::endl;
    }
    catch (int i)
    {  // Catch exceptions of type int
      std::cout << " i caught - value is " << i << std::endl;
    }
    catch (const char* message)
    {   // Catch exceptions of type char*
      std::cout << " \"" << message << "\" caught" << std::endl;
    }
    std::cout << "End of the for loop body (after the catch blocks) - i is "
      << i << std::endl;
  }
}
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <exception>

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



PreviousNext

Related