写一个catch子句时必须指明异常对象是如何传递到这个子句来的,三种方式:
接下来比较它们使用时会出现的问题,以说明最好的选择是by reference。
class exception //标准异常类
{
public:
virtual const char* what() throw();
};
class runtime_error://标准异常类
public exception{...}
class Validation_error //重新定义的异常类
public exception
{
public:
virtual const char* what() throw();
}
void someFunction()
{
...
if(失败)
throw Validation_error();
}
void doSomething()
{
try{
someFunction();
}
catch(exception ex)
{
cerr << ex.what(); //调用的exception::what
} //而不是Validation_error::what
}
调用的是基类的what函数——即使抛出的异常属于Validation_error类型,而Validation_error重新定义了虚函数。
void doSomething()
{
try{
someFunction();
}
catch(exception& ex) //catch by reference
{
cerr << ex.what();
//调用的是Validation_error::what
// 而非exception::what
}
}
最佳的捕捉异常方式:catch by reference。
(catch子句内增加一个&符号)