Question: USING C++ Exception Specifications If a function does not catch an exception, it should at least warn programmers that any invocation of the function might

USING C++

Exception Specifications If a function does not catch an exception, it should at least warn programmers that any invocation of the function might possibly throw an exception. If there are exceptions that might be thrown, but not caught in the function definition, then those exception types should be listed in an exception specification, which is illustrated by the following:

double safe_divide(int top, int bottom) throw (DivideByZero);

The exception specification must appear in both the function declaration and the function definition. If a function has more than one declaration, all function declarations must have the same exception specification. The exception specification is also referred to as a throw-list.

If more than one exception is thrown in a function, then they are separated by commas:

void some_function( ) throw (DivideByZero, OtherException);

If an exception is thrown into a function but that function does not include the specification, then the program ends once it has reached the exception situation.

Experiment 1 The following program solves a quadratic equation. Use the concepts that you have learned in this activity to rewrite the program such that it uses the exception handlers to handle exceptional situations.

// Program to solve quadratic equation #include #include #include

using namespace std; void all_zero( ); void roots(double a, double b, double c);

int main( ) { double a, b, c; // coefficient of ax^2 + bx + c = 0 cout << "Enter the three coefficients "; cin >> a >> b >> c;

roots(a, b, c);

return 0; }

void all_zero( ) { exit(1); }

void roots(double a, double b, double c) { double x1, x2; // The two roots double temp;

if( !(a == 0 && b == 0 && c == 0) ) { 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 "; exit(1); }

} else { cout << "Division by zero, not defined "; exit(1); } } else { all_zero( ); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!