The Anomaly class (exception classes) consists of 4 base classes, Bad_cast, Bad_alloc,runtime_error, Logic_error;
Runtime_error: Errors can be detected only when the program is running;
Logic_error: A logic error detected by the application.
Where Bad_cast, Bad_alloc uses the default constructor, Runtime_error, Logic_error, must be initialized with a string (C-style or STL);
User-defined classes can also inherit (inherit) from the exception class and initialize the corresponding parameters;
The code is as follows:
* * * cppprimer.cpp * * Created on:2013.11.28 * author:caroline//*eclipse CDT, gcc 4.8.1*/ /* setlocale Example * * #include <iostream> #include <string> #include <stdexcept> usin
G namespace Std; Class Out_of_stock:public Std::runtime_error {public://Initialize Runtime_error explicit out_of_stock of the base class (const
std::string &s): Std::runtime_error (s) {}}; Class Id_mismatch:public Std::logic_error {public:explicit id_mismatch (const std::string &s): Std::logi
C_error (s) {} id_mismatch (const std::string &s, const std::string &LHS, const std::string &RHS):
Std::logic_error (s), left (LHS), right (RHS) {} const std::string left, right;
}; struct My_food {my_food (const std::string FI, const int fn): food_id (FI), Food_num (FN) {} my_food& Ope
rator+= (const my_food& RHS);
Std::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 (void) {My_food M1 ("Apple", 3), M2 ("Pear", 2), M3 ("Apple", 2);
try{M1 + = M3;
Std::cout << m1.food_id << ":" << m1.food_num << Std::endl;
M1 + = M2; }catch (const Id_mismatch &e) {std::cerr << e.what () << ": Left ID (" << e.l
EFT << ") Right ID (" << e.right << ")" << Std::endl; }
}
Output:
Apple:5
wrong Id:left ID (Apple) Right ID (Pear)
Author: csdn Blog spike_king
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/