参见英文答案 >
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.
这正是您在代码中所做的.
因此,无论您的期望是什么,我都会说这是预期的行为.
请注意,您可以交换两个处理程序来解决问题.