4.9.7 获得更多的调试信息
exception提供了方便的存储信息能力,可以向它添加任意数量的信息,但当异常对象被用operator<<多次追加数据时,会导致它存储有大量的信息(BOOST_THROW_EXCEPTION就是个很好的例子)。如果还是采用自由函数get_error_info来逐项检索的话可能会很麻烦甚至不可能,这时我们需要另外一个函数:diagnostic_information()。
diagnostic_information()可以输出异常包含的所有信息,如果异常是由宏BOOST_THROW_ EXCEPTION抛出的,则可能相当多并且不是用户友好的,但对于程序开发者可以提供很好的诊断错误的信息。
示范BOOST_THROW_EXCEPTION和diagnostic_information()用法的代码如下:
- #include <boost/exception/all.hpp>
- using namespace boost;
- struct my_err{}; //自定义的异常类
- int main()
- {
- using namespace boost;
- try
- {
-
- //使用enable_error_info包装自定义异常
- throw enable_error_info(my_err())
- << errinfo_errno(101)
- << errinfo_api_function("fopen");
- }
- catch (boost::exception& e)
- {
- cout << diagnostic_information(e)<<endl;
- }
-
- try
- {
- BOOST_THROW_EXCEPTION(std::logic_error("logic")); //必须是标准异常
- }
- catch (boost::exception& e)
- {
- cout << diagnostic_information(e)<<endl;
- }
- }
程序运行结果可能如下:- Throw in function (unknown)
- Dynamic exception type: struct boost::exception_detail::error_info_injector<stru
- ct my_err>
- [struct boost::errinfo_api_function_ *] = fopen
- [struct boost::errinfo_errno_ *] = 101, "Unknown error"
-
- xxx.cpp(65): Throw in function int __cdecl main(void)
- Dynamic exception type: class boost::exception_detail::clone_impl<struct boost::
- exception_detail::error_info_injector<class stlpd_std::logic_error> >
- std::exception::what: logic
运行结果显示了普通的throw语句与BOOST_THROW_EXCEPTION的不同,后者可以显示出更多对调试有用的信息。
exception库里还有一个更方便的函数current_exception_diagnostic_ information(),它只能在catch块内部使用,以std::string返回异常的诊断字符串,这免去了指定异常参数的小麻烦。