打印不带有nested_ptr的nested_exception [英] Print nested_exception with no nested_ptr

查看:133
本文介绍了打印不带有nested_ptr的nested_exception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用来自 cppreference.com <的以下示例代码来打印嵌套异常/ a>:

I'm trying to print nested exceptions using the following example code from cppreference.com:

void print_exception(const std::exception& e, int level =  0)
{
    std::cerr << std::string(level, ' ') << "exception: " << e.what() << '\n';
    try {
        std::rethrow_if_nested(e);
    } catch(const std::exception& e) {
        print_exception(e, level+1);
    } catch(...) {}
}

但是,我如果最里面的异常是 std :: nested_exception 而不是 std :: exception (即我抛出的异常)一个 std :: nested_exception ,捕获它,然后应用 print_exception )。

However, I get an abort if the innermost exception is a std::nested_exception rather than a std::exception (IE I throw a std::nested_exception, catch it, and then apply print_exception).

这是一个最小的示例:

int main() {
    try {
        std::throw_with_nested( std::runtime_error("foobar") );
    } catch(const std::exception& e1) {
        std::cerr << e1.what() << std::endl;
        try {
            std::rethrow_if_nested(e1);
        } catch( const std::exception& e2 ) {
            std::cerr << e2.what() << std::endl;
        } catch( ... ) {
        }
    } catch ( ... ) {
    }
}

它将终止:

foobar
terminate called after throwing an instance of 'std::_Nested_exception<std::runtime_error>'
  what():  foobar
Aborted (core dumped)

文档对于 std :: throw_with_nested 指出


nested_exception基的默认构造函数类调用
std :: current_exception,在std :: exception_ptr

The default constructor of the nested_exception base class calls std::current_exception, capturing the currently handled exception object, if any, in a std::exception_ptr


$ b $中捕获当前处理的异常
对象(如果有)。 b

,因此我希望 e1 源自 std :: nested_exception 但没有 nested_ptr 。为什么 std :: rethrow_if_nested 无法处理?对我来说,处理这种情况的最佳方法是什么?

so I would expect e1 to derive from std::nested_exception but have no nested_ptr. Why does std::rethrow_if_nested not handle this? What is the best approach for me to handle this case?

推荐答案

您可以编写以下内容:

// Similar to rethrow_if_nested
// but does nothing instead of calling std::terminate
// when std::nested_exception is nullptr.

template <typename E>
std::enable_if_t<!std::is_polymorphic<E>::value>
my_rethrow_if_nested(const E&) {}

template <typename E>
std::enable_if_t<std::is_polymorphic<E>::value>
my_rethrow_if_nested(const E& e)
{
    const auto* p = dynamic_cast<const std::nested_exception*>(std::addressof(e));

    if (p && p->nested_ptr()) {
        p->rethrow_nested();
    }
}

演示

这篇关于打印不带有nested_ptr的nested_exception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆