Catch exception thrown from memory references

By default an exception can only occur during a function call or a throw. If we needs to catch excpetions thrown from trapping instructions, using the `-fnon-call-exceptions`.

Docs:

-fnon-call-exceptions

Generate code that allows trapping instructions to throw exceptions. Note that this requires platform-specific runtime support that does not exist everywhere. Moreover, it only allows trapping instructions to throw exceptions, i.e. memory references or floating point instructions. It does not allow exceptions to be thrown from arbitrary signal handlers such as SIGALRM. 

Example:

#include <iostream>
 
#include <signal.h>
 
using namespace std;
 
static void
sigsegv_handler (int signo)
{
    throw 0;
}
 
int
main (int argc, char *argv[])
{
    int *ptr = nullptr;
    int res;
 
    signal (SIGSEGV, sigsegv_handler);
 
    try {
        res = *ptr;
    } catch (...) {
        cout << "exception" << endl;
    }
 
    return res;
}
g++ -fnon-call-exceptions -o sig sig.cpp

Refernces:
[1] https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html

Leave a Reply

Your email address will not be published. Required fields are marked *