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

Get the what() message of boost::exception

本文关键字:what 消息 boost exception 获取      更新时间:2023-10-16

在下面的代码中,我想获取 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;但我找不到拥有它的方法。提升异常系统对我来说是个谜。

如何获得此消息?

编辑:提升::异常没有what()方法。那么,由于这不是std::exception,外壳如何写std::exception::what: bad lexical cast: source type value could not be interpreted as target呢?

将其

捕获为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

来自diagnostic_information_what参考:

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

该函数不应该给你来自what()函数的消息,它应该在what()函数用于创建要返回的消息。

然后继续,从boost::lexical_cast参考:

如果转换不成功,则会引发bad_lexical_cast异常。

那么让我们来看看bad_lexical_cast

class bad_lexical_cast : public std::bad_cast

它继承自标准std::bad_cast继承自具有what()成员函数的std::exception

所以解决方案是捕获boost::bad_lexical_cast(或std::exception),而不是完全不涉及boost::exception