C++ 標準庫提供結構化的異常類層次,理解其設計可編寫更精準的錯誤處理代碼。
std::exception
├── std::logic_error // 邏輯錯誤:可預防(前置條件違反)
│ ├── domain_error // 定義域錯誤(數學函數參數域)
│ ├── invalid_argument // 無效參數
│ ├── length_error // 長度超限
│ └── out_of_range // 越界訪問
├── std::runtime_error // 運行時錯誤:難預防(外部條件)
│ ├── range_error // 結果範圍錯誤
│ ├── overflow_error // 上溢
│ └── underflow_error // 下溢
├── std::bad_alloc // 記憶體分配失敗(new 失敗)
├── std::bad_cast // dynamic_cast 失敗
├── std::bad_typeid // typeid(nullptr)
├── std::bad_exception // unexpected_handler 拋出
├── std::bad_weak_ptr // weak_ptr 鎖定失敗
└── std::ios_base::failure // IO 流錯誤
| 異常類 | 分類 | 構造函數 | 用途 |
|---|---|---|---|
bad_alloc |
運行時 | **僅預設構造** `bad_alloc()` | `new` 失敗,無額外信息需求 |
bad_cast |
運行時 | **僅預設構造** `bad_cast()` | `dynamic_cast` 失敗 |
runtime_error |
運行時 | **必須帶字符串** `runtime_error(const string&)` | 外部條件導致錯誤(IO、網路、資源耗盡) |
logic_error |
邏輯 | **必須帶字符串** `logic_error(const string&)` | 程式邏輯缺陷(前置條件違反、API 誤用) |
// 1. 繼承適當基類
class ConfigError : public std::runtime_error {
public:
explicit ConfigError(const std::string& msg) : runtime_error(msg) {}
// 可添加額外診斷數據
int line_number;
std::string file_name;
};
// 2. 提供便利工廠函數
[[noreturn]] void throwConfigError(const std::string& msg, int line, const std::string& file) {
ConfigError e(msg);
e.line_number = line;
e.file_name = file;
throw e;
}
// 3. 異常安全:析構函數不拋出、資源用 RAII 管理
// 4. 文檔化:Doxygen @throw 標註函數可能拋出的異常
try {
riskyOperation();
}
catch (const ConfigError& e) { // 最具體優先
logError(e.what(), e.line_number);
}
catch (const std::runtime_error& e) { // 類別捕獲
logError("Runtime: " + std::string(e.what()));
}
catch (const std::exception& e) { // 標準異常基類
logError("Std: " + std::string(e.what()));
}
catch (...) { // 兜底:非標準異常、C 異常
logError("Unknown exception");
throw; // 重拋或轉換
}
善用標準異常體系,讓錯誤處理具備分類清晰、診斷豐富、恢復可控的工程品質。