2

如何在 C++ 中捕获错误的数组引用?为什么以下代码不起作用:

    #include <exception>

    int * problemNum = new int;
    int (* p [100])() = {problem1, problem2, problem3};

    ...

    try {
        cout << (*p[*problemNum-1])();
    }
    catch (exception){
        cout << "No such problem";
    }

我的编译器说:Euler.exe 中 0xcccccccc 处的未处理异常:0xC0000005:访问冲突。当我通过输入0*problemNum 来启动错误引用时。

4

2 回答 2

4

alamar 是对的——C++ 不会用这种类型的数组捕获异常。

改用 STL 向量:

#include <exception>
#include <vector>

int * problemNum = new int;
std::vector<int(*)()> p;
p.push_back(problem1);
p.push_back(problem2);
p.push_back(problem3);

...

try {
    cout << p.at(*problemNum-1)();
}
catch (exception){
    cout << "No such problem";
}
于 2009-05-22T22:22:21.597 回答
3

因为 C++ 无法通过其异常机制处理此类错误。有关该问题,请参阅有缺陷的 C++ 。

使用sigaction(2).

sigaction - 检查和更改信号动作

概要

   #include <signal.h>

   int sigaction(int signum, const struct sigaction *act,
                 struct sigaction *oldact);

描述 sigaction() 系统调用用于更改进程在接收到特定信号时采取的操作。signum 指定信号并且可以是除 SIGKILL 和 SIGSTOP 之外的任何有效信号。如果 act 不为空,则从 act 安装信号 signum 的新动作。如果 oldact 不为 null,则前一个操作保存在 oldact 中。sigaction 结构定义为:

       struct sigaction {
           void     (*sa_handler)(int);
           void     (*sa_sigaction)(int, siginfo_t *, void *);
           sigset_t   sa_mask;
           int        sa_flags;
           void     (*sa_restorer)(void);
       };

您需要捕获 SIGSEGV,您可以附加自己的处理程序(执行非法内存访问时调用的函数)。

于 2009-05-22T22:10:26.567 回答