我得到一个分段故障,而不是一个异常

编程入门 行业动态 更新时间:2024-10-28 02:30:39
本文介绍了我得到一个分段故障,而不是一个异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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/signal-handling-in-linux

Read more about signals here: www.alexonlinux/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.

更多推荐

我得到一个分段故障,而不是一个异常

本文发布于:2023-08-05 17:09:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1306862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是一个   而不   故障   异常

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!