1

使用 Boost.Exception 引发异常时遇到问题。8444950934950830985903859380958309850938905839859080985098940689089689028

class BOOST_SYMBOL_VISIBLE base_exception : virtual public std::exception, virtual public boost::exception
{
public:
    base_exception()
    : std::exception(),
      boost::exception(),
      context_(0)
    {
    }

    base_exception(const char* context)
    : std::exception(),
      boost::exception(),
      context_(context)
    {
    }

    virtual ~base_exception() BOOST_NOEXCEPT_OR_NOTHROW
    {
    }

protected:
    const char* context_;
};

class BOOST_SYMBOL_VISIBLE my_exception : public virtual base_exception
{
public:
    my_exception(const char* context)
       : base_exception(context)
    {
    }

    my_exception(const my_exception& other)
       : base_exception(other)
    {
    }

    virtual char const* what() const BOOST_NOEXCEPT_OR_NOTHROW
    {
        return "my exception";
    }

    virtual ~my_exception() BOOST_NOEXCEPT_OR_NOTHROW
    {
    }
};

BOOST_NORETURN void throw_exception(const base_exception& ex)
{
    BOOST_THROW_EXCEPTION(ex << boost::errinfo_api_function("api_1"));
}

BOOST_NORETURN void throw_exception(const my_exception& ex)
{
    BOOST_THROW_EXCEPTION(ex << boost::errinfo_api_function("api_2"));
}

int main(void) {
    try{
        throw_exception(my_exception("context"));
    }catch(...)
    {
        cerr << boost::current_exception_diagnostic_information();
    }
    return 0;
}

这个程序的结果是:

Throw location unknown (consider using BOOST_THROW_EXCEPTION)
Dynamic exception type: boost::wrapexcept<my_exception>
std::exception::what: my exception

但是如果将此 my_exception 更改为 base_exception

.../main.cpp(59): Throw in function void throw_exception(const base_exception &)
Dynamic exception type: boost::wrapexcept<base_exception>
std::exception::what: std::exception
[boost::errinfo_api_function_*] = api_1

为什么BOOST_THROW_EXCEPTION不输出异常的来源和原因?如何修复此代码?

4

0 回答 0