我无法捕获并处理浮点异常? [英] I cannot catch and handle floating point exception?

查看:49
本文介绍了我无法捕获并处理浮点异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to write a simple program to practicing Expection of C++, but I cannot catch and handle floating point exception?

这是我的代码.

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

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

This is my result, but is not I want.

0 / 3 = 0
2 / 2 = 1
4 / 1 = 4
Floating point exception (core dumped)

推荐答案

浮点异常"是信号的名称( SIGFPE ).如果尝试将整数除以0(或者将 INT_MIN 除以 -1 ),则会收到此信号.换句话说,它与浮点运算或异常(在C ++意义上)无关,因此该名称有点不幸.

"Floating point exception" is the name of a signal (SIGFPE). You get this signal if you try to divide an integer by 0 (or if you divide INT_MIN by -1). In other words, it has nothing to do with floating point operations or exceptions (in the C++ sense), so the name is a bit unfortunate.

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

The easiest solution is to check for 0 beforehand:

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];

这篇关于我无法捕获并处理浮点异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆