Rethrowing exceptions - C++ Statement

C++ examples for Statement:try catch

Description

Rethrowing exceptions

Demo Code

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

class Trouble/* w  ww  . j ava  2  s.  c om*/
{
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
    {
      try
      {
        if (i == 3)
          throw trouble;
        else if (i == 5)
          throw moreTrouble;
        else if(i == 6)
          throw bigTrouble;
      }
      catch (const Trouble& t)
      {
        if (typeid(t) == typeid(Trouble))
          std::cout << "Trouble object caught in inner block: " << t.what() << std::endl;
        else
          throw t;                            // Throw current exception
      }
    }
    catch (const Trouble& t)
    {
      std::cout << typeid(t).name() << " object caught in outer block: " << t.what() << std::endl;
    }
    std::cout << "End of the for loop (after the catch blocks) - i is " << i << std::endl;
  }
}

Result


Related Tutorials