Print nested_exception with no nested_ptr

后端 未结 1 948
清歌不尽
清歌不尽 2021-01-22 16:54

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)
         


        
相关标签:
1条回答
  • 2021-01-22 17:21

    You may write something like:

    // 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();
        }
    }
    

    Demo

    0 讨论(0)
提交回复
热议问题