Monday, April 11, 2011

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?

From stackoverflow
  • 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.

    janneb : Note that the option -mcheck-zero-division is specific to the MIPS architecture. E.g. it won't work on x86.
    lakshmanaraj : Yes you are right, we need to go for SIGFPE handler..
  • No - there is no exception thrown (you get a signal - probably SIGFPE). You need to check for possible divide by zeros in your code, and then throw an exception yourself,

  • If this causes a run-time error at all (see lakshmanaraj's nice discussion on IEEE maths, though some compiler will let you force errors instead of NaNs), it throws a floating point exception signal.

    Signals are a different mechanism than c++ exceptions, and are handled at the OS level. There are already a number of SO questions concerning the *nix signal mechanism, including:

    For windows, you'll have to ask someone else. Mac OS X is--of course-- a unix derived system.

    Jared Oberhaus : Windows has its own mechanism called Structured Exception Handling, You'll see it abbreviated as SEH: http://msdn.microsoft.com/en-us/library/ms680657(VS.85).aspx

0 comments:

Post a Comment