View Full Version : Exception Handling Problem
Jay I
03-19-2008, 06:14 AM
Hi guys!
I'm new to programming in C++ on Linux so i run into a strange problem. I was trying to catch segmentation fault but i couldnt. Though i placed try..catch block around the code that tries to write some value to the begining of RAM my program successfully crashed and i only saw "SegmentationFault" as its output. So my question is how to catch segmentation faults in C++ on Linux. Any help appreciated.
matsp
03-19-2008, 06:30 AM
You can use "signal()" to catch a segment fault.
http://www.hmug.org/man/3/signal.php
Segmentation fault is number 11 (SIGSEGV).
Note however that it's not guaranteed that you can continue from a SIGSEGV - but you should be able to catch the fault.
--
Mats
brewbuck
03-19-2008, 09:22 AM
Note however that it's not guaranteed that you can continue from a SIGSEGV - but you should be able to catch the fault.
Just don't try to be clever by throwing a C++ exception from inside the SIGSEGV handler. It would be awesome if that worked, but it doesn't.
According to POSIX, the behavior of a program is undefined after it received an asynchronous SIGSEGV. In practice, many system will attempt to retry the faulting instruction after the handler finishes. If you return from the signal handler, chances are it's just going to be called again, in an infinite loop. The only thing you can really do is print an error (carefully!) and call exit().
matsp
03-19-2008, 09:27 AM
According to POSIX, the behavior of a program is undefined after it received an asynchronous SIGSEGV. In practice, many system will attempt to retry the faulting instruction after the handler finishes. If you return from the signal handler, chances are it's just going to be called again, in an infinite loop. The only thing you can really do is print an error (carefully!) and call exit().
Or, you could use setjmp()/longjmp() to continue executing somewhere completely different.
--
Mats
brewbuck
03-19-2008, 11:26 AM
Or, you could use setjmp()/longjmp() to continue executing somewhere completely different.
Thereby jumping past all kinds of destructors and leaking resources right and left? ;)
But that's a problem for C programs as well. At least in C you can build an "unwind list" which you can process prior to a longjmp(). In C++ it's nearly impossible because there is no way to deliberately trigger a destructor. Well, you can call ~Class() directly, but that doesn't release memory since it has no idea whether the object is heap or stack... It's a gnarly problem.
In practice, just set a global flag from your signal handler, and periodically check it in the main body of code. If you see that it's set, THEN you can throw an exception and everything will unwind properly. But that doesn't work for SIGSEGV for reasons already mentioned...
vBulletin® v3.7.0, Copyright ©2000-2009, Jelsoft Enterprises Ltd.