我最近开始使用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;
}
答案 0 :(得分:2)
您需要重新抛出嵌套异常并检查:
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 ...;
}
}
答案 1 :(得分:1)
boost :: diagnostic_information是获取描述的正确方法。 但你也可以为boost :: error_info(T)重载to_string: http://svn.boost.org/svn/boost/trunk/boost/exception/errinfo_errno.hpp