HEV

Catch exception thrown from memory references

· hev

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

#include

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