我得到一个分段故障,而不是一个异常 [英] I get a segmentation fault instead of an exception

查看:259
本文介绍了我得到一个分段故障,而不是一个异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,在第一次迭代,我得到一个异常,而在第二个我得到一个分段错误,没有打印错误消息。似乎未捕获到异常:

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

Intel Xeon

Platform:
Linux - OpenSuse 11.4
C++ - GCC 4.5.1
Intel Xeon

推荐答案

由于segfault不是(直接)软件引起的,而是由处理器检测到您试图访问无效内存(或以无效方式访问内存 - 例如写入受写保护的内存,执行不应该被执行的内存等),它不是可捕获与 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 的信号处理程序捕获segfault。然而,Ivaylo解释说,如果你得到一个segfault,它通常不允许只是再试一次。 SIGSEGV 的信号处理程序允许 longjmp 退出 ,但不应该只是返回。

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.

这篇关于我得到一个分段故障,而不是一个异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆