Catching any exception - C++ Statement

C++ examples for Statement:try catch

Description

Catching any exception

Demo Code

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

class Trouble//from www .j  a v  a  2 s.com
{
private:
  string message;
public:
  Trouble(string str = "There's a problem") : message {str} {}

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

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

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 (...)                                // Catch any exception
      {
        std::cout << "We caught something! Let's rethrow it. " << std::endl;
        throw;                                   // Rethrow 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