0
void myterminate () 
{
   cout << "terminate handler called";
}

int main (void) 
{
   set_terminate (myterminate);
   
   throw;  // throwing an exception. So, terminate handler should be invoked 
           // as no one is handling this exception.    
   getch();
   return 0;
}

But After executing this code, the output is:

terminate handler called + "Debug Error!" dialog box appears.

I am not sure why it is coming like this !!!! Please help.

4

3 回答 3

4

Based on the MSDN documentation for set_terminate the new handler function must call exit() or abort() will be called:

The set_terminate function installs term_func as the function called by terminate. set_terminate is used with C++ exception handling and may be called at any point in your program before the exception is thrown. terminate calls abort by default. You can change this default by writing your own termination function and calling set_terminate with the name of your function as its argument. terminate calls the last function given as an argument to set_terminate. After performing any desired cleanup tasks, term_func should exit the program. If it does not exit (if it returns to its caller), abort is called.

For example:

void myterminate () 
{
   cout << "terminate handler called";
   exit(1);
}
于 2012-04-07T14:43:41.520 回答
2

According to the requirments of the standard, a function used as a terminate_handler must meet the following requirement (ISO/IEC 14882:2011 18.8.3.1):

Required behavior: A terminate_handler shall terminate execution of the program without returning to the caller.

As your function doesn't meet this requirement you program has undefined behaviour. In order to see your custom diagnostic you should output a newline to std::cout (as this can be required on many platforms) and then terminate the program in some way, such as calling std::abort.

std::abort is used to signal an abnormal termination of the program so you can expect extra diagnostics to be reported to the user such as via the dialog box that you are seeing.

Note that using std::exit from a terminate handler is potentially dangerous as std::terminate might be called in response to an exceptional condition occurring in a function registered with std::atexit or std:: at_quick_exit. This would lead to a second attempt to call std::exit.

In summary, if you don't want an "abnormal" termination, you almost always need to catch exceptions that you throw.

于 2012-04-07T14:52:58.253 回答
1

You have to exit program in your terminate handler. Add the following line to the handler and it will work:

exit(-1);
于 2012-04-07T14:43:56.810 回答