C++ 打印无嵌套\u ptr的嵌套\u异常

C++ 打印无嵌套\u ptr的嵌套\u异常,c++,c++11,exception-handling,try-catch,C++,C++11,Exception Handling,Try Catch,我正在尝试使用以下示例代码打印嵌套的异常: 它中止: foobar terminate called after throwing an instance of 'std::_Nested_exception<std::runtime_error>' what(): foobar Aborted (core dumped) foobar 在引发“std::\u嵌套\u异常”的实例后调用terminate 什么():foobar 中止(堆芯转储) forstd::throw_

我正在尝试使用以下示例代码打印嵌套的异常:

它中止:

foobar
terminate called after throwing an instance of 'std::_Nested_exception<std::runtime_error>'
  what():  foobar
Aborted (core dumped)
foobar
在引发“std::\u嵌套\u异常”的实例后调用terminate
什么():foobar
中止(堆芯转储)
for
std::throw_with_嵌套
声明

嵌套的\u异常基类调用的默认构造函数 std::current_异常,捕获当前处理的异常 std::exception\u ptr中的对象(如果有)


因此,我希望
e1
派生自
std::nested_exception
,但没有
nested_ptr
。为什么
std::rethrow\u if\u nested
不处理此问题?我处理这个案件的最佳方法是什么?

您可以这样写:

// 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();
    }
}
//如果嵌套,则类似于rethrow\u
//但是除了调用std::terminate之外,什么也不做
//当std::nested_异常为nullptr时。
模板
std::如果值>
my_rethrow_if_嵌套(常数&){
模板
std::如果启用,则启用
my_rethrow_if_嵌套(常量E&E)
{
const auto*p=dynamic_cast(std::addressof(e));
如果(p&p->nested_ptr()){
p->rethrow_nested();
}
}

std::rethrow\u如果嵌套的
将调用哪个调用
std::terminate
当没有嵌套的
ptr
时,您可以手动执行等效操作。
foobar
terminate called after throwing an instance of 'std::_Nested_exception<std::runtime_error>'
  what():  foobar
Aborted (core dumped)
// 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();
    }
}