C++庫 - <system_error>



C++中的<system_error>標頭檔案提供了一種跨不同平臺報告和處理系統相關錯誤的方法。它將特定於系統的錯誤程式碼封裝到可移植、易於處理的C++物件中,從而能夠在現代應用程式中進行錯誤處理。它將系統錯誤與特定於平臺的API解耦,提供一個抽象層,以確保在不同的作業系統上保持一致的行為。

<system_error>包含兩個類

  • error_code − 表示與特定系統錯誤關聯的錯誤程式碼。它同時包含數字錯誤值和錯誤類別。
  • system_error − 它是一個從std::runtime_error派生的異常類,用於丟擲包含系統相關錯誤資訊的異常。

包含<system_error>標頭檔案

要在你的C++程式中包含<system_error>標頭檔案,可以使用以下語法。

#include <system_error>

<system_error>標頭檔案的函式

以下是<system_error>標頭檔案中所有函式的列表。

序號 函式及描述
1 assign

它分配另一個錯誤程式碼。

2 operator=

它賦值一個錯誤程式碼。

3 clear

它清除錯誤程式碼。

4 value

它獲取error_code的值。

5 category

它獲取此error_code的error_category。

6 default_error_condition

它獲取此error_code的error_condition。

7 message

它獲取此error_code的解釋性字串。

8 operator bool

它檢查值是否非零。

非成員函式

序號 函式及描述
1 operator==

它比較兩個error_code。

2 operator!=

它比較兩個error_code。

3 operator<

它比較兩個error_code。

4 operator<=>

它比較兩個error_code。

5 operator<<

它將值和類別名稱輸出到輸出流。

建立自定義錯誤

在下面的示例中,我們將使用std::error_code來建立自定義錯誤程式碼。

#include <iostream>
#include <system_error>
int main() {
   std::error_code x(1007, std::generic_category());
   std::cout << "Error code: " << x.value() << "\n";
   std::cout << "Error message: " << x.message() << "\n";
   return 0;
}

輸出

上述程式碼的輸出如下:

Error code: 1007
Error message: Operation not permitted

處理系統錯誤

考慮以下示例,我們將丟擲一個std::system_error異常,其中包含一個指示許可權被拒絕錯誤的錯誤程式碼。

#include <iostream>
#include <system_error>
int main() {
   try {
      throw std::system_error(std::make_error_code(std::errc::permission_denied));
   } catch (const std::system_error & x) {
      std::cout << "Caught error: " << x.what() << "\n";
      std::cout << "Error code: " << x.code() << "\n";
   }
   return 0;
}

輸出

以下是上述程式碼的輸出:

Caught error: Permission denied
Error code: generic:13
廣告