#include class UnluckyNumber : public std::exception { public: UnluckyNumber(const char* msg) { mMsg = msg; } virtual const char* what() const throw() { return mMsg; } private: const char* mMsg; }; class Cow { public: Cow() { std::cout << "Moo!" << std::endl; } ~Cow() { std::cout << "x_x" << std::endl; } }; int pickANumber(int n) { std::cout << "entering pickANumber()" << std::endl; Cow c; if(n % 2 == 0){ throw UnluckyNumber("That is not a good number."); } if(n % 7 == 0){ throw UnluckyNumber("That's a terrible number!"); } std::cout << "exiting pickANumber()" << std::endl; return n; } int main(int argc, char* argv[]) { // 1 // Nothing goes wrong here // Note that the Cow is destroyed as pickANumber() exits try { std::cout << "The first number is..." << pickANumber(5) << std::endl; } catch (UnluckyNumber& e) { } // 2 // Exception! // Note that the function exit string is never printed, but the Cow is // still destroyed when the stack is unwound due to the exception. try { std::cout << "The second number is: " << pickANumber(6) << std::endl; } // We can catch *all* exceptions catch (std::exception& e){ std::cout << "some other error: " << e.what() << std::endl; } // 3 try { std::cout << "The third number is: " << pickANumber(21) << std::endl; } // Or just catch UnluckyNumber exceptions catch (UnluckyNumber& e) { std::cout << "something went horribly wrong: " << e.what() << std::endl; } return(0); }