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 跨執行緒傳遞異常。