关于标准异常中为什么要将what定义为虚函数.

bluejugar 2005-08-10 11:01:09
RT.
...全文
172 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
bluejugar 2005-08-14
  • 打赏
  • 举报
回复
还是结了吧.
visual4825 2005-08-13
  • 打赏
  • 举报
回复
那么你可以在程序中throw Derived1或Derived2,在catch时调用what()得到的信息是不同的啊.
也就是多态的一般应用而已.不知道我们说的是不是一个意思
-------------------------------------------------------
yhbttfile 2005-08-12
  • 打赏
  • 举报
回复
这样设计的目的主要是为了让标准异常具有某种层次关系。让用户有更多的选择余地。

如,你定义了:
class MathErr : public exception { /*省略定义*/ }

class DivZero : public MathErr { /*省略定义*/ }
class OverFlow : public MathErr { /*省略定义*/ }

如果用户只希望捕获数学异常,不希望做更深入的处理(如:恢复某种场景,或者调用某个后处理函数等),则可以如下操作:

try
{
// 数学计算
}
catch(MathErr &)
{
// 如,这里只简单打印:MathErr.what()
}

如果用户知道自己的运算可能溢出,这时候用户知道知道自己溢出后做一些处理(如:报告用户可能输入数值过大,可能使用的中间变量变量太小,需要提升处理的能力等)。

try
{
// 数学计算
}
catch(OverFlow &e)
{
// 经过处理,再次执行计算。
}
catch(MathErr &e) // 这里表示我不能处理的异常,
{
// 如,这里只简单打印:e.what()
throw;
}





cenlmmx 2005-08-11
  • 打赏
  • 举报
回复
没懂什么意思.如果
class Derived1 : public exception
{
.......
const char *what() const throw()
{
std::cout<<"No error"<<std::endl;
}
}
class Derived2: public exception
{
.......
const char *what() const throw()
{
std::cout<<"Error exists"<<std::endl;
}
}
那么你可以在程序中throw Derived1或Derived2,在catch时调用what()得到的信息是不同的啊.
也就是多态的一般应用而已.不知道我们说的是不是一个意思.
visual4825 2005-08-11
  • 打赏
  • 举报
回复
由于异常是基于型别差异的,不知道这里的virtual有什么用
----------------------------------------------------
class MyExcepton : public exception

catch(MyException& d)
{ d.what(); }

catch(exception& e)
{ e.what(); }
virtual不就是基于对象的dynamic type,去调用类型匹配最佳的
bluejugar 2005-08-11
  • 打赏
  • 举报
回复
to cenlmmx:
I see.
但是如果在某个地方要使用到what的话,由于异常是基于型别差异的,不知道这里的virtual有什么用.

不知道我有没有将意思说清楚.
K 2005-08-11
  • 打赏
  • 举报
回复
学习!
cenlmmx 2005-08-10
  • 打赏
  • 举报
回复
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();
};
The class serves as the base class for all exceptions thrown by certain expressions and by the Standard C++ library. The C string value returned by what() is left unspecified by the default constructor, but may be defined by the constructors for certain derived classes
上面也就是说基类的what是留下来没定义的,如果有派生类继承它,由派生类来实现.

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧