Boost C++ 库

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb SutterAndrei Alexandrescu, C++ 编码标准

Boost 异常

diagnostic_information

#include <boost/exception/diagnostic_information.hpp> 
#include <boost/exception_ptr.hpp> 

namespace
boost
    {
    template <class E>
    std::string diagnostic_information( E const & e, bool verbose=true );
    
    std::string diagnostic_information( exception_ptr const & p, bool verbose=true );
    }

返回值

一个字符串值,包含关于所传递对象的不同数量的诊断信息

  • 如果 E 可以静态转换为 boost::exception 或 std::exception,则使用 dynamic_cast 来访问 e 的 boost::exception 和 std::exception 子对象;否则,boost::diagnostic_information 模板不可用。
  • 返回的值包含通过 operator<< 存储在 boost::exception 子对象中的所有 error_info 对象的字符串表示。
  • 此外,如果 verbose 为 true,它还包含与异常相关的其他诊断信息,包括 std::exception::what() 返回的字符串。

每个 error_info 对象的字符串表示通过对 to_string(x) 的非限定调用推导得出,其中 x 的类型为 error_info<Tag,T>,Boost Exception 为其定义了一个通用重载。它将 x.value() 转换为字符串,尝试按顺序绑定(在 error_info<Tag,T> 模板实例化时)以下函数

  1. 对 to_string(x.value()) 的非限定调用(返回值应为 std::string 类型。)
  2. 对 s << x.value() 的非限定调用,其中 s 是 std::ostringstream。

第一个成功绑定的函数在调用 diagnostic_information 时使用;如果两个重载解析都不成功,则系统无法将 error_info 对象转换为字符串,并且使用未指定的存根字符串值,而不会发出编译错误。

exception_ptrdiagnostic_information 重载等效于

if( p )
    try
        {
        rethrow_exception(p);
        }
    catch(...)
        {
        return current_exception_diagnostic_information(verbose);
        }
else return <unspecified-string-value>;

示例

这是 diagnostic_information 函数的可能输出,如 libs/exception/example/example_io.cpp: 中所用:

example_io.cpp(70): Throw in function class boost::shared_ptr<struct _iobuf> __cdecl my_fopen(const char *,const char *)
Dynamic exception type: class boost::exception_detail::clone_impl<struct fopen_error>
std::exception::what: example_io error
[struct boost::errinfo_api_function_ *] = fopen
[struct boost::errinfo_errno_ *] = 2, "No such file or directory"
[struct boost::errinfo_file_name_ *] = tmp1.txt
[struct boost::errinfo_file_open_mode_ *] = rb