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

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

/*
Boost.Exception 提供了一个用以抛出异常的宏,它包含了函数名,
以及如文件名、行数的附加信息。

*/

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

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

class allocation_failed1 :
	public std::exception
{
public:
	allocation_failed1(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> allocate1(std::size_t size)
{
	/*
	通过使用宏 BOOST_THROW_EXCEPTION 替代 throw, 
	如函数名、文件名、行数之类的附加信息将自动被添加到异常中。
	但这仅仅在编译器支持宏的情况下有效。
	*/
	if (size > 1000)
		BOOST_THROW_EXCEPTION(allocation_failed1(size));
	return boost::shared_array<char>(new char[size]);
}

void save_configuration_data1()
{
	try
	{
		boost::shared_array<char> a = allocate1(2000);
		// saving configuration data ... 
	}
	catch (boost::exception &e)
	{
		e << errmsg_info("saving configuration data failed");
		throw;
	}
}

int test02()
{
	try
	{
		save_configuration_data1();
	}
	catch (boost::exception &e)
	{
		std::cerr << boost::diagnostic_information(e);
	}

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值