卓航论坛
标题:
C++的异常类(exception classes) 详解
[打印本页]
作者:
[db:作者]
时间:
2016-10-17 16:21
标题:
C++的异常类(exception classes) 详解
异常类(exception classes)包含4种基类,bad_cast, bad_alloc,runtime_error, logic_error;
runtime_error: 错误只有当程序运行时, 才能检测出来;
logic_error: 应用程序检测出的逻辑错误.
其中bad_cast, bad_alloc使用默认构造器, runtime_error, logic_error, 必须使用string(C-style或stl)进行初始化;
用户定义的类也可以继承(inherit)自异常类, 并初始化相应的参数;
代码如下:
/*
* cppprimer.cpp
*
* Created on: 2013.11.28
* Author: Caroline
*/
/*eclipse cdt, gcc 4.8.1*/
/* setlocale example */
#include [i]
#include
#include
using namespace std;
class out_of_stock : public std::runtime_error
{
public:
//初始化基类的runtime_error
explicit out_of_stock(const std::string &s) : std::runtime_error(s) {}
};
class id_mismatch : public std::logic_error
{
public:
explicit id_mismatch(const std::string &s) : std::logic_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& operator+=(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
输出:
Apple:5
wrong id: left id(Apple) right id(Pear)
作者:csdn博客 Spike_King
更多精彩内容:http://www.bianceng.cn/Programming/cplus/
作者:
方丹果舞
时间:
2016-10-17 17:17
路过,学习下
作者:
叶归尘bacal
时间:
2016-10-19 10:49
学习了,不错,讲的太有道理了
作者:
qszheng1
时间:
2016-10-21 00:21
这是什么东东啊
欢迎光临 卓航论坛 (http://vkeepw.evai.pl/)
Powered by Discuz! X3.2