I need to write a wrapper to a function. Its purpose is to cache the result and possibly exceptions of the function. It should work as follows: during the first execution it should execute the function and store the result (or exception) returned by the function. During next executions it should return previously stored result or rethrow caught exception.
The problem is, that I want to store the type of exception. So basically I want to catch every type of exception, and rethrow it in the future without losing its type.
I'm using C++ or C++11, so any solution in one of these languages would be very appreciated.
Question: What is Re-throwing an exception means in C++? A : An exception that is thrown again as it is not handled by that catching block B : An exception that is caught twice
The exception thrown from the catch block can be an exception of any type -- it doesn’t need to be the same type as the exception that was just caught. Another option is to rethrow the same exception. One way to do this is as follows: Although this works, this method has a couple of downsides.
The fact that the second line indicates that Base is actually a Base rather than a Derived proves that the Derived object was sliced. Fortunately, C++ provides a way to rethrow the exact same exception as the one that was just caught. To do so, simply use the throw keyword from within the catch block (with no associated variable), like so:
Fortunately, C++ provides a way to rethrow the exact same exception as the one that was just caught. To do so, simply use the throw keyword from within the catch block (with no associated variable), like so: Caught Base b, which is actually a Derived Caught Base b, which is actually a Derived
You're looking for std::exception_ptr
.
You can get the currently-caught exception using std::current_exception()
, store the resulting std::exception_ptr
, and throw it later with std::rethrow_exception(std::exception_ptr)
There is a good example of usage on the cppreference wiki.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With