|
#include <iostream>
#include <exception>
#include <string>
using namespace std;
class CustomException : public exception
{
private:
string reason;
public:
CustomException(string reason)
{
this->reason = reason;
}
~CustomException()
{
cout << "调用CustomException的析构函数" << endl;
}
virtual const char* what() const noexcept // throw()与noexcept等价,表明:在这个函数作用域内不可以抛出任何异常
{
return reason.c_str(); // 重载虚函数时,子类与父类各方面都必须一样
}
};
double Division(double divisor,double dividend)
{
if (dividend == 0)
{
throw CustomException("除数为零");
}
return divisor / dividend;
}
int main()
{
try
{
cout << "结果为" << Division(8, 0) << endl;
}
catch (exception& exp)
{
cout << exp.what() << endl;
}
}
请问一下,为什么catch (exception& exp)就可以正常捕获到抛出的异常CustomException("除数为零"),而catch (exception exp)就不行了呢? |
上一篇: 继承问题下一篇: 关于非模态对话框的资源销毁问题
|