C++ 異常處理使用 try-catch 結構,可拋出任意類型(int、double、類等)。標準庫提供 std::exception 及其派生類(bad_cast、runtime_error 等),但實際開發中往往需要自定義異常以攜帶更多業務信息。
std::logic_error 或 std::runtime_error,它們構造函數接受字符串參數。throw()(C++11 後建議 noexcept)承諾不拋出異常,防止析構時觸發 terminate。what()。#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
// 自定義異常類
class MyError : public logic_error {
public:
explicit MyError(const string& msg) : logic_error(msg) {}
virtual ~MyError() noexcept {} // C++11 使用 noexcept
};
// 業務類
class Sale {
int x;
public:
explicit Sale(int val) : x(val) {}
void check() {
try {
if (x > 5) throw MyError("數值超出範圍: " + to_string(x));
cout << "正常值: " << x << endl;
} catch (const MyError& e) {
cerr << "捕獲自定義異常: " << e.what() << endl;
}
}
};
int main() {
Sale s(13);
s.check();
return 0;
}
const MyError&)避免切片問題,並能多態調用 what()。在大型項目中,建議建立異常層次體系(如 AppException 為基類,派生 NetworkError、DBError 等),並在文檔中明確各層拋出的異常類型,便於上層精確捕獲處理。