LinuxSir.cn,穿越时空的Linuxsir!

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

Linux下C++如何catch系统级错误

[复制链接]
发表于 2011-1-25 23:10:44 | 显示全部楼层 |阅读模式
#include <iostream>
using namespace std;

int main()
{
    try
    {
        int i = 0;
        int j = 1;
        int k = j/i;
    }
    catch(...)
    {
        cout << "exception" << endl;
    }
    return 0;
}

g++编译时像这种exception是catch不住的。除了用信号,编译器里有没有什么选项可以控制的。Windows下有个SEH,Linux下不知道有没有对应的东西。Thanks~
发表于 2011-1-26 11:22:10 | 显示全部楼层
catch signal SIGFPE.
标准c++的异常有:
Standard exceptions
The C++ library defines a number of common exceptions. Use

    * exception
          o logic_error
                + domain_error
                + invalid_argument
                + length_error
                + out_of_range
          o runtime_error
                + range_error
                + overflow_error
                + underflow_error
还有
    * Memory allocation errors.
    * I/O errors.
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-1-26 23:00:11 | 显示全部楼层
呃,能麻烦楼上再详细点么,用信号的话程序是要这样写么:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <csignal>
using namespace std;

void signal_handler(int sig)
{
    throw "an exception";
}

int main()
{

    struct sigaction act;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    act.sa_handler = signal_handler;
    sigaction(SIGFPE, &act, NULL);

    try
    {
        int i = 0;
        int j = 1;
        int k = j/i;
    }
    catch(...)
    {
        cout << "exception" << endl;
    }
    return 0;
}

在signal_handler里抛出的异常也不能被main()里的catch捕获啊。如果在signal_handler里catch的话直接处理不就完了。我想知道Linux下有没有能将信号量和C++标准中的try...catch...结合起来的东西,写程序时就不用理会信号了,可以统一用try...catch...搞。谢谢。
回复 支持 反对

使用道具 举报

发表于 2011-1-27 16:16:14 | 显示全部楼层
可以考虑下面这种多线程设计模式。
屏蔽所有其他线程的信号,而在某个线程中调用sigwait()或者sigwaitinfo(),处理系统信号。而用其他的线程跑业务逻辑。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-1-28 06:33:30 | 显示全部楼层
好比说业务逻辑里要求某个函数发生0除异常的时候给出一个错误提示再继续执行,但要求另一个函数遇到0除异常时必须中止,多线程怎么处理这种情况。

如果try...catch...可以捕捉0除异常那就好办了,只要两个函数中的catch块中行为不同即可。但是我不知道Linux有没有提供这种机制。
回复 支持 反对

使用道具 举报

发表于 2011-1-28 09:52:02 | 显示全部楼层
I'm trying to use the siginfo_t structure that's described in Section 5.4,
"Realtime Signal Handling", of the Guide to Realtime Programming.
As I read it, when a SIGFPE is generated, siginfo_t should contain the
address of the bad instruction in member si_addr.
理论上应该可以通过si_addr来判断事故发生位置。但Linux是否实现,是个问题。你可以试试,然后告诉咱们。
回复 支持 反对

使用道具 举报

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

本版积分规则

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