Use throw_with_nested and catch nested exception

前端 未结 1 1253
臣服心动
臣服心动 2021-01-12 10:15

I really like std::throw_with_nested in c++11 since it emulates java\'s printStackTrace() but right now I am just curious how to catch a nested exception, for example:

相关标签:
1条回答
  • 2021-01-12 10:31

    Unwrapping a std::nested_exception is readily accomplished via recursion:

    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;
        }
    }
    

    Where usage would look something like this:

    try {
        throws();
    } catch(const std::exception& e) {
        try {
            rethrow_unwrapped(e);
        } catch (const SomeException& e) {
            // do something
        }
    }
    

    A demo of this in action can be found here.

    0 讨论(0)
提交回复
热议问题