// custom_exception3.cc #include #include #include #include using namespace std; class MyException: public std::exception { string Message; public: MyException(const char *msg):Message(msg) {} virtual const char* what() const throw() { return Message.c_str(); } ~MyException() throw() {} }; double SafeSqrt(double x) { if (x < 0.0) throw MyException("MyException: Tried to take sqrt of negative number"); return sqrt(x); } void ComputeRoots() { try { cout << "Square root of 4 is " << SafeSqrt(4.0) << endl; cout << "Square root of -4 is " << SafeSqrt(-4.0) << endl; } catch (MyException& ex) { cout << "Caught a sqrt exception in ComputeRoots()" << endl; } } int main() { try { ComputeRoots(); } catch (std::exception& ex) { // any std::exception incl. ours! cout << "Caught an exception in main()" << endl; cout << ex.what() << endl; } }