C++建立自定義異常的程式


異常是C++的核心概念之一。異常發生在執行過程中出現意外或不可能的操作時。處理這些意外或不可能的操作被稱為C++中的異常處理。異常處理主要使用三個特定的關鍵字完成,它們是‘try’、‘catch’和‘throw’。‘try’關鍵字用於執行可能遇到異常的程式碼;‘catch’關鍵字用於處理這些異常;‘throw’關鍵字用於建立異常。C++中的異常可以分為兩種型別:STL異常和使用者定義異常。在本文中,我們重點介紹如何建立這些自定義的使用者定義異常。更多關於異常處理的詳細資訊,請點選此處。

使用單個類建立自定義異常

首先,我們看看如何使用單個類來建立一個自定義異常。為此,我們必須定義一個類並丟擲該類的異常。

語法

//user-defined class
class Test{};
try{
   //throw object of that class
   throw Test();
}
catch(Test t) {
   ....
}

示例

#include <iostream>
using namespace std;

//define a class
class Test{};

int main() {
   try{
      //throw object of that class
      throw Test();
   }
   catch(Test t) {
      cout << "Caught exception 'Test'!" << endl;
   }

   return 0;
}

輸出

Caught exception 'Test'!

‘try’塊丟擲該類,而‘catch’塊只捕獲該特定類的異常。如果有兩個使用者定義的異常類,則必須分別處理這兩個類。

使用多個類建立自定義異常

如果有多個異常,則過程很簡單,正如預期的那樣,每個異常都必須分別處理。

語法

//user-defined class
class Test1{};
class Test2{};
try{
   //throw object of the first class
   throw Test1();
}
catch(Test1 t){
   ....
}
try{
   //throw object of the second class
   throw Test2();
}
catch(Test2 t){
   ....
}

示例

#include <iostream>
using namespace std;

//define multiple classes
class Test1{};
class Test2{};

int main() {
   try{
      //throw objects of multiple classes
      throw Test1();
   }
   catch(Test1 t) {
      cout << "Caught exception 'Test1'!" << endl;
   }
   try{
      throw Test2();
   }
   catch(Test2 t) {
      cout << "Caught exception 'Test2'!" << endl;
   }

   return 0;
}

輸出

Caught exception 'Test1'!
Caught exception 'Test2'!

我們必須使用兩個不同的try-catch塊來處理兩個不同類型別的不同異常。現在我們看看是否可以使用建構函式來建立和處理異常。

使用建構函式建立自定義異常

我們可以使用類建構函式來建立自定義異常。在下面的示例中,我們看到異常的丟擲和處理都在類建構函式本身內進行管理。

示例

#include <iostream>
using namespace std;

//define a class
class Test1{
   string str;
   public:
      //try-catch in the constructor
      Test1(string str){
         try{
            if (str == "Hello"){
               throw "Exception! String cannot be 'Hello'!";
            }
            this->str = str;   
         }
         catch(const char* s) {
            cout << s << endl;
         }
      }
};

int main() {
   Test1 t("Hello");
   return 0;
}

輸出

Exception! String cannot be 'Hello'!

異常處理是C++提供的最重要的功能之一。我們可以繼承C++異常類並用它來實現異常處理,但這只是良好的實踐,並非建立自定義異常的必要條件。繼承C++異常類的優點是,如果存在捕獲std::exception的普通catch語句,它可以處理任何使用者定義的異常,而無需瞭解具體的細節。需要注意的是,‘throw’語句只在‘try’塊內有效,否則無效。只有當用戶定義的類或某些STL類丟擲異常時,‘catch’語句才能處理該異常。

更新於:2022年12月13日

3K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

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