If you have read the Unhandled Exceptions – Handle Them article, you are already familiar with unhandled exceptions in C#. Most people don’t really know that C++ also, have a mechanism to allow a clean termination of our program. I am writing this post to introduce you with that mechanism.

 

When an exception is unhandled by our program, no cleanup occur, meaning the destructors are not called. Moreover, you may want to do operations such as logging or presenting a friendly screen announcing about the occurrence of a problem. Wrapping out Main function with a Try Catch(…) block is not recommended due to performance issues. Fortunately, the set_terminate function comes to our rescue (defined in <exception> header file).

 

The set_terminate establishes a new terminate handler to be called at the termination of the program. The default behavior of the terminate handler is to call abort and we can change this default by writing our own termination function. In a multithreaded environment, terminate functions are maintained separately for each thread so that new thread is in charge of its own termination handling. Here is the set_terminate signature:

terminate_handler
   set_terminate(
      terminate_handler _Pnew
   ) throw( );

Notice the following 3 things:

  1. This method returns the address of the previous function that used to be called at termination.
  2. The input parameter is the new function to be called at termination. Here is its signature: typedef void (*terminate_function)();
  3. Our handler is not allowed to throw any exception.

Here is a usage example:

void term_func()
{
    cout << "Terminating...\n";
    // ... cleanup tasks performed here
    abort();
}

int main( ) 
{
   set_terminate(term_func);

   // Do your stuff...
}

Hope it helps.

Tags :

Post a Comment