Вывести nested_exception без nested_ptr

Я пытаюсь распечатать вложенные исключения, используя следующий пример кода из 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 (IE я бросаю std::nested_exception, ловлю его, а затем применяю 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

поэтому я ожидал, что e1 будет производным от std::nested_exception, но не nested_ptr. Почему std::rethrow_if_nested не справляется с этим? Как мне лучше всего разобраться с этим делом?


person aaron    schedule 21.10.2016    source источник
comment
std::rethrow_if_nested вызовет rethrow_nested, который вызовет std::terminate, когда нет nested_ptr, вы можно сделать аналог вручную.   -  person Jarod42    schedule 21.10.2016


Ответы (1)


Вы можете написать что-то вроде:

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

Демо

person Jarod42    schedule 21.10.2016