#include using namespace std; class bad_thing: public exception { public: string explanation; bad_thing(string expl); virtual const char * what() const noexcept; }; bad_thing::bad_thing(string expl): explanation(expl) { } const char * bad_thing::what() const noexcept { return explanation.c_str(); } int compute(int x, int y) { int total = 0; for (int i = 0; i < x; i += 1) total += 1; for (int i = 0; i < y; i += 1) total -= 1; if (total == 7) throw bad_thing("It isn't supposed to be seven!"); return total; } int main() { int a[] = { 3, 11, 8, 15 }; int v = 15; try { cout << "The results are:\n"; for (int i = 0; i < 4; i += 1) cout << " " << compute(v, a[i]) << "\n"; cout << "That's it.\n"; } catch (bad_thing & bt) { cout << "\nFailed because of a bad thing,\n"; cout << " the explanation is \"" << bt.what() << "\"\n"; } cout << "But the program safely continues.\n"; }