首先,当一个异常产生时即调用terminate()函数,如下所示:
#include <exception>
#include <iostream>
void on_terminate()
{
std::cout << "terminate() function called!"
<< std::endl;
std::cin.get();
}
int main()
{
// for VC6, drop the 'std::' prefix
std::set_terminate( on_terminate);
throw std::exception();
std::cout << "terminate() function NOT
called!" << std::endl;
std::cin.get();
return 0;
}
避免以上异常情况的发生是很简单的,如下所示:
int main()
{
try
{
/* code
*/
}
catch( std::exception & exc)
{
// log
it, or something
}
catch(...)
{
// log
"Unknown exception"
}
return 0;
}
然而,这种方法看起来有些复杂,特别是在多线程程序中,因为在每一个线程中你必须编写如以上的catch处理。