### Throwing exceptions handler

I'm pretty new to the concept of throwing and catching exception handlers. I originally thought, that in the event of an exception to a code (in this case of the quadratic formula if a<0, the code would throw a and the project would break. What else do I need to do in order to complete the exception handler?

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748`` ``````// Test Case: Solve quadratic equations // And throws variables that are either a is less than 0 or b2 is less than 0 #include #include #include using namespace std; int main( ) { //Preconditions: a must be positive while b^2 exceeds the product 4ac //Postconditions: solves quadratic equation double a, b, c; // coefficient of ax^2 + bx + c = 0 double x1, x2; // The two roots double temp; cout << "Enter the three coefficients \n"; cin >> a >> b >> c; if(a != 0) { temp = b*b - 4*a*c; if(temp >= 0) { // Two roots x1 = ( -b + sqrt(temp))/2*a; x2 = ( -b - sqrt(temp))/2*a; cout << "The two roots are: " << x1 << " and " << x2 << endl; } else { cout << "Square root of negative values is not defined \n"; exit(1); } }else { cout << "Division by zero, not defined \n"; exit(1); } if (a<0) //throw if a is less then 0 throw a; if (b*b < 4*a*c) //throw if b^2 is less than 4ac throw temp; system ("pause"); return 0; } ``````
Last edited on
This is not a good candidate for exception handling, but here is how it might look:

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152`` ``````// Test Case: Solve quadratic equations // And throws variables that are either a is less than 0 or b2 is less than 0 #include #include #include #include #include void check_precondition(double a, double b, double c) { std::string errors; if (a == 0) errors += "a cannot be 0."; else if (a < 0) errors += "a cannot be negative."; if (b*b <= 4 * a*c) { if (!errors.empty()) errors += '\n'; errors += "b squared must be greater than 4ac\n"; } if (!errors.empty()) throw std::runtime_error(errors); } int main() { double a, b, c; try { std::cout << "Enter the three coefficients \n"; std::cin >> a >> b >> c; check_precondition(a, b, c); double discriminant = b*b - 4 * a*c; std::cout << "The two roots are: " << ((-b + std::sqrt(discriminant)) / (2 * a)); std::cout << " and " << ((-b + std::sqrt(discriminant)) / (2 * a)) << '\n'; } catch (std::exception& ex) { std::cout << "Problem encountered:\n" << ex.what() << '\n'; std::cout << "With a = " << a << ", b = " << b << ", c = " << c << '\n'; return 1; } }``````

http://ideone.com/5PUt0q
Topic archived. No new replies allowed.