jeudi 20 octobre 2016

Print nested_exception with no nested_ptr

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)
{
    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(...) {}
}

However, I get an abort if the innermost exception is a std::nested_exception rather than a std::exception (IE I throw a std::nested_exception, catch it, and then apply print_exception).

This is a minimal example:

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 ( ... ) {
    }
}

It aborts:

foobar
terminate called after throwing an instance of 'std::_Nested_exception<std::runtime_error>'
  what():  foobar
Aborted (core dumped)

The documentation for std::throw_with_nested states that

The default constructor of the nested_exception base class calls std::current_exception, capturing the currently handled exception object, if any, in a std::exception_ptr

so I would expect e1 to derive from std::nested_exception but have no nested_ptr. Why does std::rethrow_if_nested not handle this? What is the best approach for me to handle this case?

Aucun commentaire:

Enregistrer un commentaire