获取boost :: exception的what()消息

时间:2016-04-21 10:25:02

标签: c++ boost

在下面的代码中,我想获得boost :: exception的what()消息。

#include <iostream>
#include <boost/lexical_cast.hpp>
#include <boost/exception/diagnostic_information.hpp>

int main(void)
{
    try
    {
        int i(boost::lexical_cast<int>("42X"));
    }
    catch (boost::exception const &e)
    {
        std::cout << "Exception: " << boost::diagnostic_information_what(e) << "\n";
    }
    return 0;
}

当我运行它时,我收到消息:

Exception: Throw location unknown (consider using BOOST_THROW_EXCEPTION)
Dynamic exception type: boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >

但是当我没有捕获异常时,shell输出:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'
  what():  bad lexical cast: source type value could not be interpreted as target
[1]    8744 abort      ./a.out

我想要那条消息:bad lexical cast: source type value could not be interpreted as target;但我找不到拥有它的方法。对我来说,提升异常系统是一个谜。

如何得到这条消息?

编辑: boost :: exception没有what()方法。那么,shell如何写std::exception::what: bad lexical cast: source type value could not be interpreted as target,因为这不是std::exception

2 个答案:

答案 0 :(得分:4)

来自the diagnostic_information_what reference

  

diagnostic_information_what函数旨在从用户定义的std :: exception :: what()覆盖中调用。

该函数不应该从what()函数中提供消息,它应该在 {/ 1}}函数中使用来创建要返回的消息。< / p>

然后继续the boost::lexical_cast reference

  

如果转换不成功,则抛出bad_lexical_cast异常。

让我们来看看bad_lexical_cast

what()

它继承自标准 std::bad_cast,它继承自std::exception成员函数class bad_lexical_cast : public std::bad_cast

因此,解决方案是捕获what()(或boost::bad_lexical_cast)而不是std::exception,而不是boost::exception

答案 1 :(得分:4)

将其抓取为bad_lexical_cast以使用方法what()

catch (const boost::bad_lexical_cast& e)
{      //    ^^^^^^^^^^^^^^^^^^^^^^^
    std::cout << "Exception: " << e.what() << "\n";
                              //  ^^^^^^^^
}

它会显示Exception: bad lexical cast: source type value could not be interpreted as target