以下时一段关于C++异常机制的示例代码:在有异常抛出的情况下,C++会负责自动析构已创建的对象,如果在析构函数中又抛出异常(此时还未进入当前异常的处理函数),则运行时系统会调用terminate(),终止程序。
#include <iostream>
#include <cstdlib>
#include <exception>
using namespace std;
void new_terminator()
{
cout<<"Hi,I'm an new terminator,I'm in charge now"<<endl;
abort();
}
class non_fruit {};
class fruit
{
public:
void f()
{
cout<<"Before throwing out an exception"<<endl;
throw non_fruit();
cout<<"After throwing out an exception"<<endl;
}
~fruit()
{
cout<<"In the destructor of class fruit"<<endl;
throw 'c';
}
};
int main ()
{
void (*old_terminator) ()=set_terminate(new_terminator);
try
{
fruit apple;
apple.f();
}
catch(non_fruit e)
{
cout<<"inside catch for type non_fruit"<<endl;
}
catch(...)
{
cout<<"inside catch for other types"<<endl;
}
return 1;
}
#include <cstdlib>
#include <exception>
using namespace std;
void new_terminator()
{
cout<<"Hi,I'm an new terminator,I'm in charge now"<<endl;
abort();
}
class non_fruit {};
class fruit
{
public:
void f()
{
cout<<"Before throwing out an exception"<<endl;
throw non_fruit();
cout<<"After throwing out an exception"<<endl;
}
~fruit()
{
cout<<"In the destructor of class fruit"<<endl;
throw 'c';
}
};
int main ()
{
void (*old_terminator) ()=set_terminate(new_terminator);
try
{
fruit apple;
apple.f();
}
catch(non_fruit e)
{
cout<<"inside catch for type non_fruit"<<endl;
}
catch(...)
{
cout<<"inside catch for other types"<<endl;
}
return 1;
}
程序运行结果
Before throwing out an exception
In the destructor of class fruit
Hi,I'm an new terminator,I'm in charge now
忽略 (core dumped)
In the destructor of class fruit
Hi,I'm an new terminator,I'm in charge now
忽略 (core dumped)
从这个示例程序可以看出,保证析构函数不抛出异常,对于程序的健壮性的意义所在。