Chapter Contents

Previous

Next
Handling Exceptions in SAS/C

Signals

Throwing an exception from a signal handler will cause unpredictable results. Exception handling depends on examining state information saved in the stack frames for currently active functions. However, signal handlers may be invoked in situations where this state information is incompletely updated. Consequently, an exception thrown in such circumstances could cause improper operation during stack unwinding.

If it is necessary to report an event triggered by a signal as an exception, then the traditional C methods should be used to trap the signal. An exception can then be thrown outside the signal handler. The following example uses such a technique:

#include #include #include #include 
// a simple user defined class for exception reporting
class fpe_error : public std::exception {
public:
   virtual const char* what() const throw()
   {  return "fpe_error"; }
};

jmp_buf jb;

// trivial signal handler
void handler( int signum )
{
   longjmp( jb, signum );
}

// dummy example code, this always generates a SIGFPE.
void doit()
{
   raise( SIGFPE );
}

// This function "adapts" signals to exceptions.
// Since this function calls setjmp(), it should not have any try blocks 
// or autos with nontrivial destructors.
void trapper()
{
   signal( SIGFPE, handler );
   if ( setjmp( jb ) )
      throw fpe_error();

   else
   {
      doit();
      signal( SIGFPE, SIG_DFL );
   }
}

int main()
{
   try
   {
      trapper();
   }
   catch ( const std::exception& e )
   {
      cout << "Caught exception class " << e.what() << endl;
   }
}

Note:    Exception handling and signal handling use separate mechanisms in SAS/C. In particular, it is not possible to intercept a signal with a catch handler unless it has been converted to an exception, as in the example code.  [cautionend]


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.