Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

c++ - I get a segmentation fault instead of an exception

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...