首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打印没有nested_exception的nested_ptr

打印没有nested_exception的nested_ptr
EN

Stack Overflow用户
提问于 2016-10-21 03:28:34
回答 1查看 407关注 0票数 2

我试图使用cppreference.com中的以下示例代码打印嵌套异常

代码语言:javascript
复制
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 (IE抛出一个std::nested_exception,捕获它,然后应用print_exception),我就会中止。

这是一个最小的例子:

代码语言:javascript
复制
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 ( ... ) {
    }
}

它中止:

代码语言:javascript
复制
foobar
terminate called after throwing an instance of 'std::_Nested_exception<std::runtime_error>'
  what():  foobar
Aborted (core dumped)

文档 for std::throw_with_nested声明:

nested_exception基类的默认构造函数调用std::current_exception,捕获std::exception_ptr中当前处理的异常对象(如果有的话)。

因此,我希望e1std::nested_exception派生出来,但没有nested_ptr。为什么std::rethrow_if_nested不处理这个问题?我处理这个案子最好的办法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-21 12:07:33

你可以写这样的东西:

代码语言:javascript
复制
// 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();
    }
}

演示

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40167897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档