参见英文答案 >
Why Base Class catch block catch derived class object?3个
> Why throw at derived class catches by base?5个
如果我传递派生类的对象,则应调用派生类catch块.但输出表明异常是由基类捕获的.为什么?
> Why throw at derived class catches by base?5个
如果我传递派生类的对象,则应调用派生类catch块.但输出表明异常是由基类捕获的.为什么?
#include<iostream> using namespace std; class Base {}; class Derived: public Base {}; int main() { Derived d; // some other stuff try { // Some monitored code throw d; } catch(Base b) { cout<<"Caught Base Exception"; } catch(Derived d) { //This catch block is NEVER executed cout<<"Caught Derived Exception"; } getchar(); return 0; }
解决方法
该标准以(见
[except.handle]/4)工作草案为例,强调我的):
The handlers for a try block are tried in order of appearance. [Note:This makes it possible to write handlers that can never be executed,for example by placing a handler for a final derived class after a handler for a corresponding unambiguous public base class.
这正是您在代码中所做的.
因此,无论您的期望是什么,我都会说这是预期的行为.
请注意,您可以交换两个处理程序来解决问题.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。