首頁 > 後端開發 > C++ > 主體

C++程式建立自訂異常

WBOY
發布: 2023-08-26 19:53:05
轉載
948 人瀏覽過

C++程式建立自訂異常

異常是C 的一個非常核心的概念。在執行過程中發生不希望或不可能的操作時會發生異常。在C 中處理這些不希望或不可能的操作稱為異常處理。例外處理主要使用三個特定的關鍵字,它們是‘try’、‘catch’和‘throw’。 ‘try’關鍵字用於執行可能遇到異常的程式碼,‘catch’關鍵字用於處理這些異常,‘throws’關鍵字用於建立異常。 C 中的異常可以分為兩種類型,即STL異常和使用者定義的異常。在本文中,我們將重點放在如何建立這些自訂的異常。有關異常處理的更多詳細資訊可以在此處找到。

使用單一類別建立自訂例外狀況

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

文法

//user-defined class
class Test{};
try{
   //throw object of that class
   throw Test();
}
catch(Test t) {
   ....
}
登入後複製

Example

的翻譯為:

範例

#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){
   ....
}
登入後複製

Example

的翻譯為:

範例

#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區塊來處理兩個不同類別的例外。現在我們來看看是否可以使用建構函數來建立和處理異常。

使用建構函式建立自訂異常

我們可以使用類別建構子來建立自訂異常。在下面的範例中,我們可以看到異常的拋出和處理都在類別構造函數內部進行管理。

Example

的翻譯為:

範例

#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 異常類別的好處是,如果有一個普通的catch語句捕獲std::exception,它可以處理任何使用者定義的異常而不需要知道具體細節。需要注意的是,'throws'語句只在'try'區塊內起作用,否則不起作用。 'catch'語句只能處理由使用者定義的類別或某些STL類別所拋出的例外。

以上是C++程式建立自訂異常的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!