在下面的代码中,我想获取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异常系统对我来说是一个谜。

如何获得此信息?

编辑: boost::exception没有what()方法。 那么,由于它不是std::exception::what: bad lexical cast: source type value could not be interpreted as target,它如何在shell中编写std::exception呢?

最佳答案

使用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

关于c++ - 获取boost::exception的what()消息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36766740/

10-13 08:48