Boost C++ 库

……是世界上最受推崇、设计最精良的 C++ 库项目之一。 Herb SutterAndrei Alexandrescu《C++ 编码标准》

diagnostic_information - Boost C++ 函数库

Boost Exception

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 对象转换为字符串,并将使用一个未指定的占位符字符串值,而不会发出编译错误。

diagnostic_informationexception_ptr 重载等效于:

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