C++中,异常不可以忽略,当异常找不到匹配的catch字句时,会调用系统的库函数terminate()(在头文件<excpetion>中),默认情况下,terminate()函数调用标准C库函数abort()使程序终止而退出。当调用abort函数时,程序不会调用正常的终止函数,也就是说,全局对象和静态对象的析构函数不会执行。

通过使用标准的set_terminate()函数,可以设置自己的terminate()函数。自定义的terminate()函数不能有参数,而且返回值类型为void。另外,terminate函数不能返回也不能抛出异常,它必须终止程序。如果terminate函数被调用,这就意味着问题已经无法解决了。

#include <iostream>
#include <exception>
using namespace std;

void terminatorb()  //函数名字可以任意,不一定非得是terminate
{
 cout<<"I will be back!"<<endl;
 exit(0);
}void (*old_terminatea)()=set_terminate(terminatorb);


class Botch
{
public:
 class Fruit {};
 void f()
 {
  cout<<"Botch::f()"<<endl;
  throw Fruit();
 }
 ~Botch() {throw 'c';}
};

int main()
{
 try{
  Botch b;
  b.f();
 }catch(char c)
 {
  cout<<"c"<<endl;
 }
 catch(...)
 {
  cout<<"inside cathc(...)"<<endl;
 }
}