LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 876|回复: 2

为什么C++的异常不起作用

[复制链接]
发表于 2007-7-23 12:41:40 | 显示全部楼层 |阅读模式
我按照一本C++入门书上写的例子编了一个很小的C++程序如下:
#include <iostream>
using namespace std;
int main() {
   int top = 90, bottom = 0;
   cout << "top / 3 = " << top / 3 << endl;
   try {
      cout << "top / bottom = " << top / bottom << endl;
   }
   catch(...) {
      cout << "There has a exception!" << endl;
   }
   
   cout << "done!" << endl;
   return 0;
}
按照书上写的,程序应该打印"There has a exception!" 消息,然后输出 "done!" 后退出的,但是在我的机器上执行到try{ }块内的语句时就直接报告说浮点数例外,然后程序就直接退出了,catch{}语句块根本就没有起作用.但是到windows下用VC试了一下这个程序,运行一切正常,我想程序应该是没有问题的,是不是debian里有哪个包没有安装造成的啊,还望高手指点!
我使用的是debian 4.0, g++4.1.
发表于 2007-7-23 14:51:12 | 显示全部楼层
在unix/linux下,浮点数异常会引发FPE信号,你不处理信号,结果就是直接退出
  1. #include <signal.h>
  2. #include <iostream>
  3. using namespace std;
  4. void handler(int signum)
  5. {
  6.         cout << "SIGFPE caught" << endl;
  7.         exit(-1);
  8. }
  9. int main()
  10. {
  11.         signal(SIGFPE, handler);
  12.         int top = 90, bottom = 0;
  13.         cout << "top / 3 = " << top / 3 << endl;
  14.         try
  15.         {
  16.                 cout << "top / bottom = " << top / bottom << endl;
  17.         }
  18.         catch (...)
  19.         {
  20.                 cout << "There has a exception!" << endl;
  21.         }
  22.         cout << "done!" << endl;
  23.         return 0;
  24. }
复制代码
此外,代码请使用code标签,而且这篇应该贴到编程版吧
回复 支持 反对

使用道具 举报

 楼主| 发表于 2007-7-23 18:24:38 | 显示全部楼层
使用信号是可以处理,但是C++的异常机制应该也能起作用才对啊.按照书上说的,而且在VC下试的,都是可以输出"There has a exception!" 消息的,为什么LINUX下就不行呢?
哦,我是刚来的,当时以为这个问题是因为debian版本造成的,不过下午在fedora上试了一下,和debian下一样,也是对异常无反应,下一次这类问题我一定放到编程版里去,多谢提醒^_^
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表