C++ 中的異常處理機制如何工作?


在 C++ 中,異常處理是處理執行時錯誤的過程。異常是在 C++ 中執行時丟擲的事件。所有異常都派生自 std::exception 類。它是一個可以處理的執行時錯誤。如果我們不處理異常,它會列印異常訊息並終止程式。

異常在 C++ 標準中定義為 `` 類,我們可以在程式中使用它。父類-子類繼承關係如下所示:

C++ 中常見的異常類:

序號異常及描述
1std::exception
這是一個異常,也是所有標準 C++ 異常的父類。
2std::bad_cast
由 dynamic_cast 丟擲的異常。
3std::bad_exception
此異常用於處理 C++ 程式中的意外異常。
4std::bad_alloc
通常由 new 丟擲。
5std::logic_error
此異常可以透過閱讀程式碼來檢測。
6std::runtime_error
此異常無法透過閱讀程式碼來檢測。
7std::bad_typeid
由 typeid 丟擲的異常。

關鍵詞

異常處理中有 3 個關鍵詞:try、catch 和 throw。

Try/Catch 塊

在 C++ 中,異常處理使用 try/catch 語句執行。可能發生異常的程式碼放在 Try 塊中。Catch 塊用於處理異常。

示例程式碼

#include <iostream>
using namespace std;
class Sample1 {
   public:
      Sample1() {
         cout << "Construct an Object of sample1" << endl;
      }
      ~Sample1() {
         cout << "Destruct an Object of sample1" << endl;
      }
};
class Sample2 {
   public:
      Sample2() {
         int i=7;
         cout << "Construct an Object of sample2" << endl;
         throw i;
      }
      ~Sample2() {
         cout << "Destruct an Object of sample2" << endl;
      }
};
int main() {
   try {
      Sample1 s1;
      Sample2 s2;
   } catch(int i) {
         cout << "Caught " << i << endl;
   }
}

輸出

Construct an Object of sample1
Construct an Object of sample2
Destruct an Object of sample1
Caught 7

使用者自定義異常

我們可以透過繼承和重寫異常類的功能來定義我們自己的異常。

示例程式碼

#include <iostream>
#include <exception> using namespace std;
struct DivideByZero : public exception {
   const char * what () const throw () {
      return "My Exception";
   }
};
int main() {
   try {
      throw DivideByZero();
   } catch(DivideByZero& e) {
      cout << "Exception caught" << endl; cout << e.what() << endl;
   } catch(exception& e) {
   }
}

輸出

Exception caught My Exception
what() = A public method provided by exception class and it has been overridden by all the child exception classes. It returns the cause of an exception.

更新於:2019年7月30日

226 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.