PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 4, 2022

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

 August 04, 2022     c++, exception, linux, try-catch     No comments   

Issue

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;
}


Answered By - Darwin Zou
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing