I want to catch an exception and bundle it within my own exception and throw upwards

后端 未结 2 1856
走了就别回头了
走了就别回头了 2021-01-19 17:19

I have a class that manages resources. It takes a Loader class that can retrieve the resource from a path. Loader is an abstract base class, so anyone could make a new loade

2条回答
  •  醉酒成梦
    2021-01-19 18:14

    How about a nested exception?

    try { /* ... */ }
    catch (...)
    {
        throw MyException("An error occurred", std::current_exception());
    }
    

    Just make a suitable class that stores the exception:

    struct MyException : std::exception
    {
        std::string message;
        std::exception_ptr nested_exception;
    
        MyException(std::string m, std::exception_ptr e)
        : message(std::move(m))
        , nested_exception(std::move(e))
        { }
    
        // ...
    };
    

    When the exception is caught, the catcher can rethrow the nested exception:

    try { /* load resource */ }
    catch (MyException & e)
    {
        log("Resource loading failed: " + e.what());
        std::rethrow_exception(e.nested_exception);
    }
    

    In fact, this entire logic is already provided by the standard library via std::throw_with_nested.

提交回复
热议问题