#include <iostream>
#include <string>
usingnamespace std;
int main () {
int dividend, divisor = 1, quotient;
string inputStr
= "The input stream is in a failure state.";
try {
cout << "Line 4: Enter the dividend: ";
cin >> dividend;
cout << endl;
cout << "Line 7: Enter the divisor: ";
cin >> divisor;
cout << endl;
if (divisor == 0)
throw divisor;
elseif (divisor < 0)
throw string("Negative Divisor.");
elseif (!cin)
throw inputStr;
quotient = dividend / divisor;
cout << "Line 17: Quotient = " << quotient
<< endl;
}
catch (int x) {
cout << "Line 19: Division by " << x
<< endl;
}
catch (string s) {
cout << "Line 21: " << s << endl;
}
return 0;
}
The book says that I should expect bad (non integer) input to trigger the final catch block, but when I compile and run the program it returns the div-by-zero error. I suspect that the input is being coerced and is catching based on that, but I am unsure why that is the case. I checked and re-checked that I typed the example in correctly, but it is possible that I just typed something in wrong.
I would like it if someone could look this over and tell my why my experience is different from what the book tells me to expect.
Copy and paste your code into the main.cpp window.
Then click on input.txt and replace the text with 5 and p separated by a space.
Next, click on the main tab and then click Compile & Execute.
The results over on the left pane are as expected.