boost教程(十九):错误处理——exception(一)

每一部分都单独注释的,运行时取消注释,将其他部分注释起来就可以。

/*
提供了一个新的异常类 boost::exception 允许给一个抛出的异常添加信息。 
它被定义在文件 boost/exception/exception.hpp 中。 由于 Boost.Exception 中的类和函数分布在不同的头文件中, 
下面的例子中将使用 boost/exception/all.hpp 以避免一个一个添加头文件。

*/


#include <boost/exception/all.hpp> 
#include <boost/lexical_cast.hpp> 
#include <boost/shared_array.hpp> 
#include <exception> 
#include <string> 
#include <iostream> 


/*
对于任何一个可以添加到异常中的信息,可以通过定义一个派生于 boost::error_info 的数据类型,
来随时向这个异常添加信息。


第一个参数叫做标签(tag),特定用来识别新建的数据类型。 通常是一个有特定名字的结构体。
第二个参数是与存储于异常中的数据类型信息相关的。

*/
typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info;

class allocation_failed :
	public boost::exception,
	public std::exception
{
public:
	allocation_failed(std::size_t size)
		: what_("allocation of " + boost::lexical_cast<std::string>(size) + " bytes failed")
	{
	}

	virtual const char *what() const throw()
	{
		return what_.c_str();
	}

private:
	std::string what_;
};

boost::shared_array<char> allocate(std::size_t size)
{
	/*
	allocate() 抛出的异常是 allocation_failed 类型的,
	而且它同时继承了 boost::exception 和 std::exception。
	函数 allocate() 中并没有调用者名等信息,以把它加入到相关的异常中。
	*/
	if (size > 1000)
		throw allocation_failed(size);
	return boost::shared_array<char>(new char[size]);
}

void save_configuration_data()
{
	try
	{
		boost::shared_array<char> a = allocate(2000);
		// saving configuration data ... 
	}
	catch (boost::exception &e)
	{
		/*
		通过获取 tag_errmsg 以创建一个对象,它通过字符串 "saving configuration data failed" 进行初始化,
		以便通过 operator<<() 操作符向异常 boost::exception 中加入更多信息。
		然后这个异常被相应的重新抛出。
		*/
		e << errmsg_info("saving configuration data failed");
		throw;
	}
}

int test01()
{
	try
	{
		/*
		调用了一个函数 save_configuration_data() ,
		它调回了 allocate() 。 allocate() 函数动态分配内存,
		而它检查是否超过某个限度。 这个限度在本例中被设定为1,000个字节。
		*/
		save_configuration_data();
	}
	catch (boost::exception &e)
	{
		/*
		为了从一个异常中获取所有可用信息,
		可以像例子中那样在 main() 的 catch 句柄中使用函数 boost::diagnostic_information() 。
		对于每个异常,函数 boost::diagnostic_information() 不仅调用 what() 而且获取所有附加信息存储到异常中。 
		返回一个可以在标准输出中写入的 std::string 字符串。
		*/
		std::cerr << boost::diagnostic_information(e);
	}




	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值