Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rethrowing typed exception in C++ or C++11

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.

like image 451
remdezx Avatar asked Sep 02 '12 09:09

remdezx


People also ask

What is re-throwing an exception means in C++?

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

Is it possible to re-throw the same exception from the catch block?

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.

How do I re-throw an exception in C++ for a sliced object?

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:

How do you throw the same exception twice in C++?

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


1 Answers

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.

like image 162
porges Avatar answered Sep 29 '22 00:09

porges