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_failed2 :
	public std::exception
{
public:
	allocation_failed2(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> allocate2(std::size_t size)
{
	if (size > 1000)
		BOOST_THROW_EXCEPTION(allocation_failed2(size));
	return boost::shared_array<char>(new char[size]);
}

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

int main()
{
	try
	{
		save_configuration_data2();
	}
	catch (boost::exception &e)
	{
		/*
		没有使用函数 boost::diagnostic_information() 
		而是使用 boost::get_error_info() 函数来直接获取错误信息的类型 errmsg_info。
		返回值是 boost::shared_ptr 类型的智能指针。 如果传递的参数不是 boost::exception 类型的,返回的值将是相应的空指针。
		 如果 BOOST_THROW_EXCEPTION 宏总是被用来抛出异常,在这些情况下没有必要去检查返回的智能指针是否为空。
		*/
		std::cerr << *boost::get_error_info<errmsg_info>(e);
	}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值