c++linuxexceptiontry-catch

How do I catch system-level exceptions in Linux C++?


The following catch() is not called:

void test(void)
{
    int i=1,j=0,k;
    try
    {
        k = i/j;
    }
    catch(...)
    {
        ...handle it...
    }
}

Is there a way to catch this kind of exception?


Solution

  • below code implement __try/__except effect like in visual studio c++ or how to simulate __try/__except for gcc or g++

    #include <stdio.h>
    #include <signal.h>
    #include <setjmp.h>
    
    __thread jmp_buf * gThreadData; //thread local storage variable declare
    
    void FPE_ExceptionHandler(int signal)
    {
        printf("exception handler signalid=%d\n", signal);
    
        //jmp to setjmp_return and rc will equal to non zero
        longjmp(*gThreadData, 10001);
    }
    
    int main(int argc, char *argv[])
    {
        //setup a callback function for access violation exception
        signal(SIGSEGV, (__sighandler_t)FPE_ExceptionHandler);
    
        //allocate a jmp_buf struct and assign it to thread local storage pointer
        gThreadData = (jmp_buf *)(new jmp_buf);
    
        //setjmp save current thread context
        int rc = setjmp(*gThreadData);
    
        //setjmp_return
        //first time, run to here rc will equal to 0
        if (rc == 0) {
            *(int*)0 = 1; //generate a exception
        }
    
        printf("return from exception\n");
        delete (jmp_buf *)gThreadData;
    }