// custom_exception.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); } int main() { double x = -4.0, y; try { y = SafeSqrt(x); cout << "The square root of " << x << " is " << y << endl; } catch (std::exception& ex) { // any std::exception incl. ours! cout << ex.what() << endl; } }