boost 异常处理

来源:互联网 发布:广电网络河源分公司 编辑:程序博客网 时间:2024/06/06 07:21

#include <boost/asio.hpp>

#include <boost/system/system_error.hpp>

//Boost.Systemboost::system::error_code ec;string hostname=boost::asio::ip::host_name(ec);TRACE("%d\n",ec.value());//错误代码等于0表示OK,否则则是错误代码的编号TRACE("%s\n",ec.category().name());//错误代码的分类//错误代码分类定义{application_category cat;boost::system::error_code ec(1,cat);TRACE("%d,%s\n",ec.value(),ec.category().name());//1,newCategory}//boost::system::error_condition,这是一个夸平台的类,不管运行在哪个系统,产生的错误代码都是一致的//用法也和boost::system::error_code 一样boost::system::error_condition errcnd=ec.default_error_condition();TRACE("%d,%s\n",errcnd.value(),errcnd.category().name());

//boost::error_info 会产生更详细的信息方便查看信息//tag_errmsg 仅仅是一个自定义的标签,tag_errmsg 可以输入任何信息typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info; class allocation_exception : public boost::exception, public std::exception { public: allocation_exception(std::size_t size) : what_("allocation of " + boost::lexical_cast<std::string>(size) + " bytes failed") //boost::lexical_cast 将数值转换为字符串{ } virtual const char *what() const throw() { return what_.c_str(); } private: std::string what_; }; boost::shared_array<char> allocate(std::size_t size) { if (size > 1000) BOOST_THROW_EXCEPTION(allocation_exception(size)); //也可以使用throw allocation_exception(size);,BOOST_THROW_EXCEPTION支持文件名,文件行,函数名称//BOOST_THROW_EXCEPTION 获取到一个能够动态识别是否派生于 boost::exception 的函数 boost::enable_error_info()。 如果不是,他将自动建立一个派生于特定类和 boost::exception 的新异常类型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) { e << errmsg_info("saving configuration data failed"); throw; //注意,这里抛出不带任何参数,表示继续抛出e异常} } void CMFC08Dlg::OnBnClickedButton2(){//Boost.Exception try { save_configuration_data(); } catch (boost::exception &e) { /*boost::exception &e,throw 版本Throw location unknown (consider using BOOST_THROW_EXCEPTION)Dynamic exception type: class allocation_failedstd::exception::what: allocation of 2000 bytes failed[struct tag_errmsg *] = saving configuration data failed*//*boost::exception &e,BOOST_THROW_EXCEPTION 版本MFC08Dlg.cpp(261): Throw in function class boost::shared_array<char> __cdecl allocate(unsigned int)Dynamic exception type: class boost::exception_detail::clone_impl<class allocation_failed>std::exception::what: allocation of 2000 bytes failed[struct tag_errmsg *] = saving configuration data failed*/TRACE("%s\n",boost::diagnostic_information(e).c_str());//boost::diagnostic_information 会提取所有信息} catch(std::exception& e){//catch的前后顺序定义会有区别抓取的/*std::exception &eallocation of 2000 bytes failed*/TRACE("%s\n",e.what());}}