exception类的原型:
请注意观察上述类的层次结构,可以看出,标准异常都派生自一个公共的基类exception。基类包含必要的多态性函数提供异常描述,可以被重载。
class exception
{
public:
exception() throw();
exception(const exception& rhs) throw();
exception& operator=(const exception& rhs) throw();
virtual ~exception() throw();
virtual const char *what() const throw();
};
函数what():返回一个表示异常的字符串。
从exception类派生一个自己的类:
#include
#include
using namespace std;
class myexception:public exception
{
public:
myexception():exception(“一个重载exception的例子”)
{}
};
int main()
{
try
{
throw myexception();
}
catch (exception &r) //捕获异常
{
cout << “捕获到异常:” << r.what() << endl;
}
return 0;
}
程序运行,输出:
捕获到异常:一个重载exception的例子
一般的,我们直接以基类捕获异常,例如,本例中使用了
catch (exception &r)
然后根据基类的多态性进行处理,这是因为基类中的what函数是虚函数。