首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 標準異常類別體系與自訂異常

     編輯:關於C++

標準異常類別層級

  • std::exception:基底類別。
  • std::bad_alloc、std::bad_cast:預設建構函式。
  • std::runtime_error:執行期才能偵測的錯誤(需字串初始化)。
  • std::logic_error:邏輯錯誤(需字串初始化)。

自訂異常類別

繼承 runtime_error 或 logic_error,並在建構函式傳遞錯誤訊息。可額外儲存相關資訊(如衝突的 ID)。

程式碼示範

/* cppprimer.cpp
 * Created on: 2013.11.28
 * Author: Caroline
 */
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;

class out_of_stock : public runtime_error {
public:
    explicit out_of_stock(const string& s) : runtime_error(s) {}
};

class id_mismatch : public logic_error {
public:
    explicit id_mismatch(const string& s) : logic_error(s) {}
    id_mismatch(const string& s, const string& lhs, const string& rhs)
        : logic_error(s), left(lhs), right(rhs) {}
    const string left, right;
};

struct My_food {
    My_food(const string& fi, int fn) : food_id(fi), food_num(fn) {}
    My_food& operator+=(const My_food& rhs);
    string food_id;
    int food_num;
};

My_food& My_food::operator+=(const My_food& rhs) {
    if (this->food_id != rhs.food_id)
        throw id_mismatch("wrong id", this->food_id, rhs.food_id);
    this->food_num += rhs.food_num;
    return *this;
}

int main() {
    My_food M1("Apple", 3), M2("Pear", 2), M3("Apple", 2);
    try {
        M1 += M3;
        cout << M1.food_id << ":" << M1.food_num << endl;
        M1 += M2;
    } catch (const id_mismatch& e) {
        cerr << e.what() << ": left id(" << e.left
             << ") right id(" << e.right << ")" << endl;
    }
}

輸出結果

Apple:5
wrong id: left id(Apple) right id(Pear)

最佳實務

  • 異常類別應輕量、可複製,避免在擲出時再次擲出異常。
  • 使用 std::exception_ptr 跨執行緒傳遞異常。
  • 資源釋放採用 RAII,確保異常傳播時不洩漏。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved