c++ - 使用 throw_with_nested 并捕获嵌套异常

标签 c++ c++11 try-catch

我真的很喜欢 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/

相关文章:

c++ - 在 gmp 库中调用 mpz_import 期间出现段错误

c++ - 为什么 netbeans 在运行我的简单程序时卡住了?

c++ - 如何在QLabel中为QImage设置缩进?

C++:重载下标运算符(不同的返回类型)

exception - 在 if() 和 try-catch 之间进行选择

java - try-with-resources 中的 null 检查

Python 3 尝试排除问题

c++ - 返回指向子类的指针的好方法

C++ 在转换运算符和可变参数构造函数之间混淆

c++ - 函数是否可能只接受给定参数的一组有​​限类型?