抽象基類
<system_error>

std::error_category

class error_category;
錯誤類別
此型別用作特定類別型別的基類。

類別型別用於標識錯誤的來源。它們還定義了其類別下 error_codeerror_condition 物件之間的關係,以及為 error_code 物件設定的 message

這些型別的物件沒有獨立的數值,不可複製且不可賦值,因此只能透過引用傳遞。因此,每種型別的物件只能存在一個,每個物件唯一地標識其自身的類別:同一類別的所有錯誤程式碼和錯誤條件應返回對同一物件的引用。

某些標準物件是派生自此類的一個型別。透過為每個標準物件呼叫特定的全域性函式可以獲取其引用。
標頭檔案類別函式
<system_error>generic_category
system_category
<ios>
<iostream>
iostream_category
<future>future_category

成員函式(非虛)


虛成員函式


示例

為了建立自定義錯誤類別,程式應派生自error_category基類並根據需要重寫虛擬函式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// custom error_category example
#include <iostream>       // std::cout, std::endl
#include <system_error>   // std::is_error_condition_enum, std::error_category,
                          // std::error_condition, std::error_code
#include <string>         // std::string

// custom error conditions enum type:
enum class custom_errc { success=0, client_error, server_error, other };
namespace std {
template<> struct is_error_condition_enum<custom_errc> : public true_type {};
}

// custom category:
class custom_category_t : public std::error_category {
public:
  virtual const char* name() const { return "custom"; }
  virtual std::error_condition default_error_condition (int ev) const {
    if ((ev>=200)&&(ev<300)) return std::error_condition(custom_errc::success);
    else if ((ev>=400)&&(ev<500)) return std::error_condition(custom_errc::client_error);
    else if ((ev>=500)&&(ev<600)) return std::error_condition(custom_errc::server_error);
    else return std::error_condition(custom_errc::other);
  }
  virtual bool equivalent (const std::error_code& code, int condition) const {
    return *this==code.category() &&
           static_cast<int>(default_error_condition(code.value()).value())==condition;
  }
  virtual std::string message(int ev) const {
    switch (ev) {
      case 200: return "OK";
      case 403: return "403 Forbidden";
      case 404: return "404 Not Found";
      case 500: return "500 Internal Server Error";
      case 503: return "503 Service Unavailable";
      default: return "Unknown error";
    }
  }
} custom_category;

// make_error_code overload to generate custom conditions:
std::error_condition make_error_condition (custom_errc e) {
    return std::error_condition(static_cast<int>(e), custom_category);
}

int main()
{
  // let's generate a 404:
  std::error_code e (404, custom_category);

  if (e == custom_errc::success) std::cout << "Success: " << e.message();
  else if (e == custom_errc::client_error) std::cout << "Client Error: " << e.message();
  else if (e == custom_errc::server_error) std::cout << "Server Error: " << e.message();
  else std::cout << "Unknown";
  std::cout << std::endl;

  return 0;
}

輸出
Client Error: 404 Not Found