问题
I have a problem with the floating point exception. When i divide by zero, i get this exception. I tried to catch it, but the solutions on the internet don't work for me.
#include<iostream>
using namespace std;
int main(){
double h{0};
int a{0},b{0},c{0};
cin.exceptions(ios_base::failbit);
cout << "Enter Values: ";
try{
cin >> a >> b >> c;
h = (3/1/a+1/b+1/c);
if(a == 0 || b == 0 || c == 0){
throw overflow_error("Division by zero is not allowed!");
}
cout << h;
}
catch(overflow_error e){
cerr << e.what();
}
catch(exception& e){
cerr << "Only numbers!";
}
catch(...){
cerr << "?";
}
return 0;
}
回答1:
You’re getting a “floating point exception” (which is not a C++ exception), that's why its not catchable.
https://www.quora.com/Why-isn%E2%80%99t-this-catch-block-in-C++-catching-any-exception
I suggest guarding for input validation.
In your code, the exception happens before you start throwing stuff.
来源:https://stackoverflow.com/questions/55451506/floating-point-exception-not-catchable