【问题标题】:Get the what() message of boost::exception获取 boost::exception 的 what() 消息
【发布时间】:2016-04-21 10:25:02
【问题描述】:

在下面的代码中,我想得到一个 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() 方法。那么,shell 怎么写std::exception::what: bad lexical cast: source type value could not be interpreted as target,因为这不是std::exception

【问题讨论】:

标签: c++ boost


【解决方案1】:

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

【讨论】:

  • 非常感谢。基类怎么可能不包含纯虚方法 what() ?为什么会有这样的选择?
  • 它从std::bad_cast 继承what(),如看到的here,它继承自std::exception
  • 这很奇怪。我认为 boost 的每个异常都来自唯一的boost::exception,例如std::exception
  • boost::exception 不等同于std::exception。它提供了不同的功能,并且在大多数情况下,Boost 库抛出的异常都源自两者。在您的代码中,您很少需要捕获 boost::exception,并且通常希望捕获 std::exception 或任何预期由库抛出的最终异常类型。
【解决方案2】:

来自the diagnostic_information_what reference

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

该函数不应该向您提供来自 what() 函数的消息,它应该在 what() 函数中用于创建要返回的消息。

然后继续,从the boost::lexical_cast reference:

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

那么让我们看看bad_lexical_cast

class bad_lexical_cast : public std::bad_cast

它继承自标准std::bad_cast,后者继承自std::exception,后者具有what() 成员函数。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-17
    • 2017-01-26
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    相关资源
    最近更新 更多