Throwing and catching objects in a hierarchy - C++ Statement

C++ examples for Statement:try catch

Description

Throwing and catching objects in a hierarchy

Demo Code

#include <iostream>
#include <string>
using std::string;

class Trouble//www  . j  a  v a2  s . c o m
{
private:
  string message;
public:
  Trouble(string str = "There's a problem") : message {str} {}

  virtual ~Trouble(){}                               // Virtual destructor
  virtual string what() const { return message; }
};

// Derived exception class
class MoreTrouble : public Trouble
{
public:
  MoreTrouble(string str = "There's more trouble...") : Trouble {str} {}
};

// Derived exception class
class BigTrouble : public MoreTrouble
{
public:
  BigTrouble(string str = "Really big trouble...") : MoreTrouble {str} {}
};


int main()
{
  Trouble trouble;
  MoreTrouble moreTrouble;
  BigTrouble bigTrouble;

  for (int i {}; i < 7; ++i)
  {
    try
    {
      if (i == 3)
        throw trouble;
      else if (i == 5)
        throw moreTrouble;
      else if(i == 6)
        throw bigTrouble;
    }
    catch (const BigTrouble& t)
    {
      std::cout << "BigTrouble object caught: " << t.what() << std::endl;
    }
    catch (const MoreTrouble& t)
    {
      std::cout << "MoreTrouble object caught: " << t.what() << std::endl;
    }
    catch (const Trouble& t)
    {
      std::cout << "Trouble object caught: " << t.what() << std::endl;
    }
    std::cout << "End of the for loop (after the catch blocks) - i is " << i << std::endl;
  }
}

Result


Related Tutorials