浮点异常不可捕获

floating point exception not catchable?

本文关键字:异常      更新时间:2023-10-16

浮点异常有问题。当我除以零时,我得到这个异常。我试图抓住它,但互联网上的解决方案对我不起作用。

#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;
}

你得到一个"浮点异常"(这不是一个C++异常(,这就是为什么它无法捕获。

https://www.quora.com/Why-isn%E2%80%99t-this-catch-block-in-C++-catching-any-exception

我建议保护输入验证。

在你的代码中,异常发生在你开始抛出东西之前。