// Example program : exceptions with constructors and destructors using namespace std; #include // the standard string library #include // for cout class light { string description; public: // constructor: light(const string d = "whatever") : description(d) { cout << "Light turned on: " << description << endl; } // destructor: ~light(){ cout << "Light turned off: " << description << endl; } }; int fourth_level(){ light xxx("red"); throw string("something unusual"); // complicated stuff return 4; } int third_level(){ light xxx("green"); cout << "+++ third-level manual setup" << endl; int rslt = 3*fourth_level(); cout << "+++ third-level manual cleanup" << endl; return rslt; } int second_level(){ light xxx("blue"); // complicated stuff return 2*third_level(); } int main(){ try { // will print 24, unless there is an exception: cout << second_level() << endl; } catch (int foo) { cout << "Caught int exception: " << foo << endl; } catch (string foo) { cout << "Caught string exception: " << foo << endl; } }