一个例子
#include<iostream>
#include <string>
using namespace std;
class Person
{
private:
int age;
string name;
public:
void setAge(int);
void setName(string);
};
class Error
{
public:
virtual void show()=0;
};
class nameError:public Error
{
public:
void show()
{
cout<<"name is error"<<endl;
}
};
class ageError:public Error
{
public:
void show()
{
cout<<"age is error"<<endl;
}
};
void Person::setAge(int a)
{
ageError ag;
if(a<0||a>100)
throw ag;
this->age=a;
}
void Person::setName(string str)
{
nameError ne;
if(str=="exit")
throw ne;
this->name=str;
}
int main(void)
{
Person p;
try
{
p.setAge(0);
p.setName("exit");
}
catch(Error &er)
{
er.show();
}
cout<<"hello world"<<endl;
return 0;
}
C++异常处理的真正能力,不仅在于它能处理各种不同类型的异常,还在于它具有在异常抛弃前为构造的所有局部对象,自动调用析构函数的能力。对象在出了作用域,都会被析构。
(1) C++中析构函数的执行不应该抛出异常;
(2) 假如析构函数中抛出了异常,那么你的系统将变得非常危险,也许很长时间什么错误也不会发生;但也许你的系统有时就会莫名奇妙地崩溃而退出了,而且什么迹象也没有,崩得你满地找牙也很难发现问题究竟出现在什么地方;
(3) 当在某一个析构函数中会有一些可能(哪怕是一点点可能)发生异常时,那么就必须要把这种可能发生的异常完全封装在析构函数内部,决不能让它抛出函数之外(这招简直是绝杀!呵呵!);
(4) 主人公阿愚吐血地提醒朋友们,一定要切记上面这几条总结,析构函数中抛出异常导致程序不明原因的崩溃是许多系统的致命内伤!