//---------------------------------------------------------------- // // exception.cpp // // Illustrating the use of assert, try, catch and throw. We use our // old familar point class. // // written by: Simon Parsons // modified : March 1st 2009 // //---------------------------------------------------------------- #include #include using namespace std; //---------------------------------------------------------------- // // Class definition // Class point represents a location in a set of cartesian coordinates. // // It has two data members, an x and a y value, and three constructors. // The constructors initialise the data members. class point { public: point() : x(0), y(0) { } // Default constructor point(double u ) : x(u), y(0) { } // Convert double to point point(double u, double v ) // Initialise both x and y if we are : x(u), y(v) { } // given values for them. void print() const; void set(double u); // We overload the function set. void set(double u, double v); private: double x, y; }; // Member functions of point. Print the values and set the values. void point::print() const { cout << "(" << x << "," << y << ")\n"; } // end of print() // Here's a version of set, with one argument, which uses assert. void point::set(double u) { assert(u > 0); x = u; y = 0; } // end of set() // Here's a version of set, with two arguments, that uses an try, throw // catch exception handler. void point::set(double u, double v) { string str = "Everything is cool!"; try{ if(!(u > 0)){ // Test for the exception. If throw u; // there is a problem, correct it } else{ x = u; // Else use the exception handling throw str; // mechanism to say everything is ok. } } catch(double u){ // A catch to handle a double cout << "That value of x is no good" << endl; cout << "I'm setting x to zero" << endl; x = 0; } catch(string s){ // A catch to handle a string. cout << s << endl; } y = v; // Now that we're done with error // handling, set y. } // end of set() //---------------------------------------------------------------- // // The main program // This creates three instances of point, creating them in different ways, and // then printing out their contents. int main() { point a; double p; double q; cout << "Enter an x-coordinate. Zero or below will the assert "; cin >> p; a.set(p); cout << "point a = "; a.print(); cout << "Enter an x-coordinate. Zero or below will the exception handler "; cin >> p; cout << "Enter a y-coordinate "; cin >> q; a.set(p, q); cout << "now, point a = "; a.print(); } // end of main()