floating point exception not catchable?

我的未来我决定 提交于 2019-12-25 01:55:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!