我无法捕获和处理浮点异常?

Gra*_*cat 6 c++

我尝试编写一个简单的程序来练习ExpectionC++,但我无法捕获和处理浮点异常?

这是我的代码。

#include <iostream>                                              
#include <string>                                                
#include <exception>                                             

using namespace std;                                             

int main(int argc, char **argv) {                                

    int num_1[] = {0, 2, 4, 6, 8}, num_2[] = {3, 2, 1, 0, -1};   

    for(int i = 0; i < sizeof(num_1) / sizeof(num_1[0]); i++) {  
        try {                                                    
            int result = num_1[i] / num_2[i];                    
            printf("%d / %d = %d\n", num_1[i], num_2[i], result);
        } catch(exception &e) {                                  
            cout << e.what() << endl;                            
            cout << "something is wrong." << endl;               
            continue;                                            
        }                                                        
    }                                                            

    return 0;                                                    
}                                                                

Run Code Online (Sandbox Code Playgroud)

这是我的结果,但不是我想要的。

0 / 3 = 0
2 / 2 = 1
4 / 1 = 4
Floating point exception (core dumped)
Run Code Online (Sandbox Code Playgroud)

mel*_*ene 4

“浮点异常”是信号的名称 ( SIGFPE)。如果您尝试将整数除以 0(或除以 ),您会收到此INT_MIN信号-1。换句话说,它与浮点运算或异常(C++意义上的)无关,所以这个名字有点不幸。

最简单的解决方案是预先检查 0:

if (num_2[i] == 0 || (num_1[i] == INT_MIN && num_2[i] == -1)) {
    // handle error, or throw your own exception
    ...
}
int result = num_1[i] / num_2[i];
Run Code Online (Sandbox Code Playgroud)