在 C++ 中捕获基类和派生类异常


要同时捕获基类和派生类的异常,我们需要把派生类的 catch 块放在基类之前。否则,派生类的 catch 块将永远不会被触及。

算法

Begin
   Declare a class B.
   Declare another class D which inherits class B.
   Declare an object of class D.
   Try: throw derived.
   Catch (D derived)
      Print “Caught Derived Exception”.
   Catch (B b)
      Print “Caught Base Exception”.
End.

这里有一个简单的示例,派生类的 catch 已被置于基类的 catch 之前,现在检查输出

#include<iostream>
using namespace std;
class B {};
class D: public B {}; //class D inherit the class B
int main() {
   D derived;
   try {
      throw derived;
   }
   catch(D derived){
      cout<<"Caught Derived Exception"; //catch block of derived class
   }
   catch(B b) {
      cout<<"Caught Base Exception"; //catch block of base class
   }
   return 0;
}

输出

Caught Derived Exception

这里有一个简单的示例,基类的 catch 已被置于派生类的 catch 之前,现在检查输出

#include<iostream>
using namespace std;

class B {};
class D: public B {}; //class D inherit the class B
int main() {
   D derived;
   try {
      throw derived;
   }
   catch(B b) {
      cout<<"Caught Base Exception"; //catch block of base class
   }
   catch(D derived){
      cout<<"Caught Derived Exception"; //catch block of derived class
   }
   return 0;
}

输出

Caught Base Exception
Thus it is proved that we need to put catch block of derived class before the base class. Otherwise, the catch block of derived class will never be reached.

更新时间:2019 年 7 月 30 日

1K+ 浏览量

开启您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.