我真的很喜欢 c++11 中的 std::throw_with_nested,因为它模拟了 java 的 printStackTrace() 但现在我只是好奇如何捕获嵌套异常,例如:
void f() {
try {
throw SomeException();
} catch( ... ) {
std::throw_with_nested( std::runtime_error( "Inside f()" ) );
}
}
void g() {
try {
f();
} catch( SomeException & e ) { // I want to catch SomeException here, not std::runtime_error, :(
// do something
}
}
以前,我认为 std::throw_with_nested 会生成一个新的异常,该异常是从两个异常(std::runtime_error 和 SomeException)中相乘派生的,但是在阅读了一些在线教程之后,它将 SomeException 封装在 std::exception_ptr 中,这可能就是为什么我不能捕获它。
然后我意识到我可以通过使用 std::rethrow_if_nested( e ) 来解决这个问题,但上面的情况只有两层,这很容易处理,但考虑到更一般的情况,比如 10 层折叠,我只是不想写 std::rethrow_if_nested 10 次来处理它。
如有任何建议,我们将不胜感激。
最佳答案
解包一个 std::nested_exception
很容易通过递归完成:
template<typename E>
void rethrow_unwrapped(const E& e)
{
try {
std::rethrow_if_nested(e);
} catch(const std::nested_exception& e) {
rethrow_unwrapped(e);
} catch(...) {
throw;
}
}
用法看起来像这样:
try {
throws();
} catch(const std::exception& e) {
try {
rethrow_unwrapped(e);
} catch (const SomeException& e) {
// do something
}
}
可以找到实际演示 here .
关于c++ - 使用 throw_with_nested 并捕获嵌套异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34754068/