Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch Segfault or any other errors/exceptions/signals in C++ like catching exceptions in Java

I wrote a Linux program based on a buggy open source library. This library sometimes triggers segfaults that I cannot control. And of course once the library has segfaults, the entire program dies. However, I have to make sure my program keeps running even if the library has segfaults. This is because my program sort of serves as a "server" and it needs to at least tell the clients something bad happened and recover from the errors, rather than chicken out... Is there any way to do that?

I understand in Java one just needs to catch an exception. But how does C++ handle this?

[UPDATE]I understand there is also exception handling in C++, but Segfault is not an exception, is it? I don't think anything is thrown when segfault happens. You have to explicitly "throw" something to use try.... catch.... as far as I know.

Thanks so much, I am quite new to C++.

like image 560
CuriousMind Avatar asked May 15 '11 12:05

CuriousMind


People also ask

Is a Segfault 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.

What catch all exceptions?

It is an event which is thrown at runtime. It protects the code and run the program even after throwing an exception. Exception handling is used to handle the exceptions. We can use try catch block to protect the code. Catch block is used to catch all types of exception.

How do you catch exceptions?

The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.

Which errors Cannot be handled by catch block?

As is documented, try/catch blocks can't handle StackOverflowException and OutOfMemoryException.


1 Answers

You cannot reliably resume execution after a segmentation violation. If your program must remain running, fence off the offending library in a separate process and communicate with it over a pipe. When it takes a segmentation violation, your program will notice the closed pipe.

like image 119
Sam Miller Avatar answered Sep 24 '22 18:09

Sam Miller