c – 当我抛出派生类的对象时,为什么捕获基类的块正在捕获异常?

参见英文答案 > Why Base Class catch block catch derived class object?3个
> 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.

这正是您在代码中所做的.
因此,无论您的期望是什么,我都会说这是预期的行为.

请注意,您可以交换两个处理程序来解决问题.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...