#include #include using namespace std; class OpenError {}; class ArithmeticError {}; class DivideByZeroError : public ArithmeticError {}; class NegativeRootError : public ArithmeticError { public: NegativeRootError(double val) : value(val) {} double getValue() const {return value;} private: double value; }; void find_roots(const double a, const double b, const double c, double &r1, double &r2) throw (ArithmeticError); int main() { ifstream in; string filename; double a, b, c, root1, root2; cout << "Please input the file name containing the coefficients: "; cin >> filename; try { in.open(filename.c_str()); if (!in) { throw OpenError(); } } catch(OpenError) { in.clear(); cerr << "File " + filename + " not found, please re-enter: "; cin >> filename; in.open(filename.c_str()); if (!in) { cerr << "You're a loser\n"; exit(0); } } in >> c >> b >> a; cout << a << " " << b << " " << c << endl; if (!in.good()) { cout << "Please enter the missing value: "; cin >> a; cout << a << " " << b << " " << c << endl; } try { cout << "Before the first call to find_roots\n"; find_roots(a, b, c, root1, root2); cout << "After the first call to find_roots\n"; } catch (DivideByZeroError) { cerr << "Error: find_roots(): coefficient 'a' is zero\n"; cout << "Before the second call to find_roots\n"; find_roots(a+1, b, c, root1, root2); cout << "After the second call to find_roots\n"; } catch (NegativeRootError e) { cerr << "Error: find_roots(): discriminent has value " << e.getValue() << endl; } catch (ArithmeticError) { cerr << "Error: find_roots(): unspecified arithmetic error\n"; } catch (...) { cerr << "Error: unknown exception thrown\n"; } cout << "The roots of " << a << "x^2 + " << b << "x + " << c << " are " << root1 << " and " << root2 << endl; return 0; } void find_roots(const double a, const double b, const double c, double &r1, double &r2) throw (ArithmeticError) { if (a == 0.0) { throw DivideByZeroError(); } double denom = 2.0 * a; double discrim = b * b - 4.0 * a * c; if (discrim < 0.0) { throw NegativeRootError(discrim); } throw OpenError(); cout << "Calculating the roots ... \n"; r1 = (-b + sqrt(discrim)) / denom; r2 = (-b - sqrt(discrim)) / denom; }