Отпечатайте 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 (т.е. хвърлям 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