在 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.