我最近开始使用 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/