Question: Modify Listing 15.11 so that the two exception types are classes derived from the logic_error class provided by the header file. Have each what() method
Modify Listing 15.11 so that the two exception types are classes derived from the logic_error class provided by the header file. Have each what() method report the function name and the nature of the problem. The exception objects need not hold the bad values; they should just support the what() method.


Here’s a sample run of the program, one that gets terminated by bad input for the gmean() function:
Enter two numbers: 4 12
Harmonic mean of 4 and 12 is 6
Geometric mean of 4 and 12 is 6.9282
Enter next set of numbers : 5 -5
hmean(5, -5): invalid arguments: a = -b
Try again.
5 -2
Harmonic mean of 5 and -2 is -6.66667
gmean() arguments should be >= 0
Values used: 5, -2
Sorry, you don't get to play any more.
Bye!
One point to notice is that the bad_hmean handler uses a continue statement, whereas the bad_gmean handler uses a break statement. Thus, bad input to hmean() leads the program to skip the rest of the loop and start the next loop cycle. But bad input for gmean() terminates the loop.This illustrates how a program can determine which exception is thrown (by the exception type) and tailor the response to the exception. A second point to notice is that the bad_gmean design illustrates techniques that are different from what bad_hmean uses. In particular, bad_gmean uses public data and a method that returns a C-style string.
Listing 15.11 error4.cpp //error4.cpp - using exception classes #include #include // or math.h, unix users may need -lm flag #include "exc_mean.h" // function prototypes double hmean (double a, double b); double gmean (double a, double b); int main() { using std::cout; using std::cin; using std::endl; double x, y, z; cout < < "Enter two numbers: "; while (cin >> x >> y) { try { // start of try block z hmean (x,y); cout < < "Harmonic mean of " < < x < < " and " < < y < < " is " < < Z < < endl; cout < < "Geometric mean of " < < x < < " and " < < y " is " < < gmean (x, y) < < endl; cout < < "Enter next set of numbers : "; }// end of try block catch (bad_hmean & bg) { bg.mesg(); cout < < "Try again. "; // start of catch block
Step by Step Solution
3.56 Rating (153 Votes )
There are 3 Steps involved in it
include include include using namespace std class ba... View full answer
Get step-by-step solutions from verified subject matter experts
