我得到分段错误而不是异常
在下面的代码中,在第一次迭代中出现异常,在第二次迭代中出现分段错误,没有打印任何错误消息.似乎没有捕获到异常:
In the following code, at the first iteration I get an exception, and at the second one I get a segmentation fault with no error message printed. It seems the exception is not caught:
int i = 0;
while(i++ < 10)
{
try {
cout << "Iteration: " << i << endl;
// Code...
cout << "OK" << endl;
}
catch(...)
{
cerr << "Error message" << endl;
continue;
}
}
Output:
Iteration 1
Error message
Iteration 2
Segmentation fault
这是正常的,还是真的有问题?
Is it normal, or there is something really wrong going on?
如果它应该是相关的,在那个代码块中我重置了一个 MySQL 连接,当我检查连接是否关闭时会生成异常.
In case it should be relevant, in that code block I reset a MySQL connection, and the exception is generated when I check if the connection is closed.
谢谢.
平台:
Linux - OpenSuse 11.4
C++ - GCC 4.5.1
英特尔至强
Platform:
Linux - OpenSuse 11.4
C++ - GCC 4.5.1
Intel Xeon
推荐答案
由于段错误不是(直接)由软件引起的,而是由处理器检测到您试图访问无效内存(或访问无效内存方式 - 例如写入受写保护的内存,执行不应该执行的内存等),它不是可捕获"的 try/catch
,旨在捕获软件引发异常.它们都称为异常,但它们起源于系统软件/硬件的不同级别.
Since segfaults are not caused (directly) the the software, but rather by the processor detecting that you are trying to access invalid memory (or access memory in an invalid way - e.g writing to memory that is write-protected, executing memory that isn't supposed to be executed, etc), it is not "catchable" with try/catch
, which is designed to catch software that throws an exception. They are both called exceptions, but they originate at different levels of the software/hardware of the system.
从技术上讲,您可以使用 SIGSEGV
的信号处理程序来捕获段错误.但是,正如 Ivaylo 解释的那样,如果您遇到段错误,通常不允许重试".SIGSEGV
的信号处理程序允许 longjmp
或 exit
,但不应只返回.
Technically, you can catch segfaults with a signal handler for SIGSEGV
. However, as Ivaylo explains, it's is not, typically, allowed to just "try again" if you get a segfault. The signal hander for SIGSEGV
is allowed to longjmp
or exit
, but shouldn't just return.
在此处阅读有关信号的更多信息:http://www.alexonlinux.com/signal-handling-in-linux
Read more about signals here: http://www.alexonlinux.com/signal-handling-in-linux
可以毫无问题地重试典型的 C++ 异常(throw
的结果)(当然,同样的异常当然可能会再次抛出.
Typical C++ exceptions (result of throw
) can be retried without problem (of course, the same exception may be thrown again, of course.
相关文章