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?
// Test Case: Solve quadratic equations
// And throws variables that are either a is less than 0 or b2 is less than 0
#include <iostream>
#include <cstdlib>
#include <cmath>
usingnamespace 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;
}
// Test Case: Solve quadratic equations
// And throws variables that are either a is less than 0 or b2 is less than 0
#include <string>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <stdexcept>
void check_precondition(double a, double b, double c)
{
std::string errors;
if (a == 0)
errors += "a cannot be 0.";
elseif (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;
}
}