I get a segmentation fault instead of an exception

两盒软妹~` 提交于 2019-12-21 04:51:14

问题


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?

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.

Thank's.


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


回答1:


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.

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.

Read more about signals here: http://www.alexonlinux.com/signal-handling-in-linux

Typical C++ exceptions (result of throw) can be retried without problem (of course, the same exception may be thrown again, of course.




回答2:


You can not catch segmentation fault like that. This error is usually unrecoverable and is not handled by the usual try-catch. It means something went very wrong probably stack corruption or similar. Try using valgrind to detect what causes the segmentation fault.




回答3:


catch clauses catch exceptions that are thrown by throw expressions. In standard C++ (and in any sane C++ implementation) they do not catch errors detected by the operating system or by the hardware. To do otherwise would make it far too hard to write exception-safe code.



来源:https://stackoverflow.com/questions/14899749/i-get-a-segmentation-fault-instead-of-an-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!