C++ - 异常类(exception classes) 的 详解 及 代码

C++ - 异常类(exception classes) 的 详解 及 代码

 

本文地址: http://blog.csdn.net/caroline_wendy/article/details/17498665

 

异常类(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 <iostream>
#include <string>
#include <stdexcept>

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 << M1.food_id << ":" << M1.food_num << std::endl;
		M1 += M2;
	}catch(const id_mismatch &e){
		std::cerr << e.what() << ": left id("
				<< e.left <<") right id(" << e.right << ")" << std::endl;
	}
}


输出:

 

 

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

 

 

 

 

 

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Caroline S

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值