C++ try catch exceptions with a base class handler
#include <iostream> #include <string> using std::string; class Trouble//from w ww. java 2 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 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; } }