#include #include #include using namespace std; #ifdef GNU_EXCEPTION_BUG #include "exceptions.h" #endif class logic_error : public exception { protected: char msg[80]; public: const char* what() const throw() { return msg; } }; class domain_error : public logic_error { public: domain_error(char* s) { strcpy (msg, s); } }; class out_of_range : public logic_error { public: out_of_range(char* s) { strcpy (msg, s); } }; double mysqrt( double x ) throw( domain_error ) { if( x < 0 ) throw domain_error( "sqrt of neg number" ); else return sqrt( x ); } double myexp( double x ) throw( out_of_range ) { double result = exp( x ); // call routines in cmath if( result == HUGE_VAL ) throw out_of_range( "exp too large" ); else return result; } double f( double x ) { try { return mysqrt( x ) + myexp( x ); } catch( logic_error & e ) { cout << "Caught exception " << e.what( ) << endl; // invoke correct what return -1.0; // can’t be answer for any other x } } int main( ) { cout << f( 10.0 ) << endl; cout << f( -4.0 ) << endl; // illegal sqrt cout << f( 10000000.0 ) << endl; // illegal exp return 0; }