我试图使用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)文档 for std::throw_with_nested声明:
nested_exception基类的默认构造函数调用std::current_exception,捕获std::exception_ptr中当前处理的异常对象(如果有的话)。
因此,我希望e1从std::nested_exception派生出来,但没有nested_ptr。为什么std::rethrow_if_nested不处理这个问题?我处理这个案子最好的办法是什么?
发布于 2016-10-21 12:07:33
你可以写这样的东西:
// 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();
}
}演示
https://stackoverflow.com/questions/40167897
复制相似问题