c++ - 我如何从 boost::errinfo_nested_exception 中提取任何信息?

标签 c++ exception boost

我最近开始使用 boost::exception。现在我想使用 boost::errinfo_nested_exception 打印有关错误原因的信息。问题是我无法弄清楚如何从原因中获取信息。我尝试了以下但没有成功:

#include <iostream>
#include <boost/exception/all.hpp>

struct myex : public virtual boost::exception {};

int main()
{
   myex cause;
   cause << boost::errinfo_file_name("causefile.cpp");

   try {
      myex ex;
      ex << boost::errinfo_nested_exception(boost::copy_exception(cause));
      throw ex;
   }
   catch (myex& e) {
      // Here I would like to extract file name from cause and print
      // it in a nice way, but I cant figure out what to do with a
      // boost::exception_ptr.
      const boost::exception_ptr* c = 
         boost::get_error_info<boost::errinfo_nested_exception>(e);

      // I cant do this:  
      // const std::string* file = boost::get_error_info<boost::errinfo_file_name>(*c);

      // Nor this: 
      // const std::string* file = boost::get_error_info<boost::errinfo_file_name>(**c);

      // This works fine and the nested exception is there, but that's not what I want.
      std::cout << boost::diagnostic_information(e) << std::endl;
   }

   return 0;
}

最佳答案

您需要重新抛出嵌套异常并检查:

const boost::exception_ptr* c = 
    boost::get_error_info<boost::errinfo_nested_exception>(e);
if(c) try {
    boost::rethrow_exception(*c);
} catch(boost::exception const& e) { // or a type derived from it
    const std::string* file = boost::get_error_info<boost::errinfo_file_name>(e);
    // ...
} catch(...) {
    // presumably you don't want the exception to escape if it is
    // not derived from boost::exception
}

我个人使用 get_error_info返回 boost::get_error_info<some_error_info>(e) 结果的包装器, 或者如果没有找到 get_error_info<some_error_info>(nested) 的结果(这里递归调用)或0如果没有嵌套异常(或者未启用 error_info)。

或者/作为补充,您可以将上面的检查代码(不同的 catch 子句)分解为一个函数:

std::string const* // or return a tuple of what you examined etc.
examine_exception()
{
    try {
        throw; // precondition: an exception is active
    } catch(boost::exception const& e) {
        // as above
        return ...;
    }
}

关于c++ - 我如何从 boost::errinfo_nested_exception 中提取任何信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6843602/

相关文章:

c++ - Boost 1.64 是否支持 HP-UX?

c++ - 什么是 C++ bool myVar : 1?

c++ - 无法在 openGL 和 GLUT 中为我想要的确切对象制作动画

c++ - 编写返回 C++ 对象的函数的最佳方法是什么?

ruby - 为什么定义的输入变量在异常发生后返回nil?

c++ - BOOST 如何在线程中发送信号并在另一个线程中执行相应的槽?

c++ - 为什么 `std::experimental::make_array` 不能使用 `std::reference_wrapper` ?

java - 正确使用 RuntimeException?

java - 为什么 RuntimeException 不需要显式异常处理?

c++ - boost .Python : Callbacks to class functions