问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/40167897/print-nested-exception-with-no-nested-ptr