我尝试编写一个简单的程序来练习C ++的Expection
,但是我无法捕获并处理浮点异常?
这是我的代码。
#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;
}
这是我的结果,但不是我想要的。
0 / 3 = 0
2 / 2 = 1
4 / 1 = 4
Floating point exception (core dumped)
答案 0 :(得分:1)
“浮点异常”是信号(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];
答案 1 :(得分:1)
谢谢大家,在您的帮助下,我理解了我的错误。很抱歉,我无法回复每条评论。请允许我整理出有用的答案。
这是我的新代码。
#include <iostream>
#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 {
if(num_2[i] == 0 || (num_1[i] == INT32_MIN && num_2[i] == -1)) {
throw "catch my expection";
}
cout << num_1[i] << " / " << num_2[i] << " = " << num_1[i] / num_2[i] << endl;
} catch(const char *e_msg) {
cout << e_msg << endl;
cout << "sth is error" << endl;
continue;
}
}
return 0;
}
这是我想要的结果。
0 / 3 = 0
2 / 2 = 1
4 / 1 = 4
catch my expection
sth is error
8 / -1 = -8