设为首页 加入收藏

TOP

4.9.7 获得更多的调试信息
2013-10-07 15:01:00 来源: 作者: 【 】 浏览:65
Tags:4.9.7 获得 更多 调试 信息

4.9.7  获得更多的调试信息

exception提供了方便的存储信息能力,可以向它添加任意数量的信息,但当异常对象被用operator<<多次追加数据时,会导致它存储有大量的信息(BOOST_THROW_EXCEPTION就是个很好的例子)。如果还是采用自由函数get_error_info来逐项检索的话可能会很麻烦甚至不可能,这时我们需要另外一个函数:diagnostic_information()。

diagnostic_information()可以输出异常包含的所有信息,如果异常是由宏BOOST_THROW_ EXCEPTION抛出的,则可能相当多并且不是用户友好的,但对于程序开发者可以提供很好的诊断错误的信息。

示范BOOST_THROW_EXCEPTION和diagnostic_information()用法的代码如下:

  1. #include <boost/exception/all.hpp> 
  2. using namespace boost;  
  3. struct my_err{};                                        //自定义的异常类  
  4. int main()  
  5. {  
  6.     using namespace boost;  
  7.     try  
  8.     {  
  9.  
  10.         //使用enable_error_info包装自定义异常  
  11.         throw enable_error_info(my_err())   
  12.             << errinfo_errno(101)  
  13.             << errinfo_api_function("fopen");  
  14.     }  
  15.     catch (boost::exception& e)  
  16.     {  
  17.         cout << diagnostic_information(e)<<endl;  
  18.     }  
  19.  
  20.     try  
  21.     {  
  22.         BOOST_THROW_EXCEPTION(std::logic_error("logic"));   //必须是标准异常  
  23.     }  
  24.     catch (boost::exception& e)  
  25.     {  
  26.         cout << diagnostic_information(e)<<endl;  
  27.     }  
  28. }  

程序运行结果可能如下:
  1. Throw in function (unknown)  
  2. Dynamic exception type: struct boost::exception_detail::error_info_injector<stru 
  3. ct my_err> 
  4. [struct boost::errinfo_api_function_ *] = fopen  
  5. [struct boost::errinfo_errno_ *] = 101, "Unknown error"  
  6.  
  7. xxx.cpp(65): Throw in function int __cdecl main(void)  
  8. Dynamic exception type: class boost::exception_detail::clone_impl<struct boost::  
  9. exception_detail::error_info_injector<class stlpd_std::logic_error> > 
  10. std::exception::what: logic  

运行结果显示了普通的throw语句与BOOST_THROW_EXCEPTION的不同,后者可以显示出更多对调试有用的信息。

exception库里还有一个更方便的函数current_exception_diagnostic_ information(),它只能在catch块内部使用,以std::string返回异常的诊断字符串,这免去了指定异常参数的小麻烦。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇4.9.4 更进一步的用法 下一篇4.5.4 特化ADL可找到的swap

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: