Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 553
slashmais Avatar asked Dec 07 '22 08:12

slashmais


1 Answers

Please check http://linux.die.net/man/1/gcc there is a compiler option -mcheck-zero-division to handle this.

Alternatively, installing a SIGFPE handler might be an option, A float div by 0 would then generate a 'FPE_ZERODIVIDE'

         signal(SIGFPE, (fptr) FPE_ExceptionHandler);

         void FPE_ExceptionHandler(int nSig,int nErrType,int */*pnReglist*/)
          {
                switch(nErrType)
                  {
                    case FPE_ZERODIVIDE:  /* ??? */ break;
                }

            }

since

Most floating point systems are based on the IEEE standard, which allows division by 0. This returns either positive infinity or negative infinity as appropriate based on the signs of the numbers. (Except 0/0 returns the undefined NAN--again not an exceptional case.) This tends to be useful for scientific and mathematical applications. The NANs effectively signal a case where calculations were not pssible but allow calculations to continue. The continued calculations will not produce new results but will continue to return NANs. This allows long long chains of calculations to be performed witout error checking within the calculatiosn. The error checks only need to be performed at the very end of the work. This makes the code much much simpler and also faster. It can also be more useful at times as for some applications, infintity is a "useful" result, not really a sign of problems.

like image 127
lakshmanaraj Avatar answered Dec 15 '22 00:12

lakshmanaraj