The goal is to fully process a loop and throw any exception that may have occurred afterwards:
for (...) {
try {
// code that could throw
} catch (const ExceptionObj &ex) {
// save ex and rethrow after the loop
}
}
What would be the best practice for doing this? Saving any of the exceptions is ok in my particular case.
A couple of ideas that I have:
Copy ex
to an ExceptionObj
value. Problem: doesn't scale well at all when ex has subclasses or more exceptions need to be handled.
Have a clone
method in ExceptionObj
that returns a copy on the heap. Problem: doesn't work for third party exceptions.
Handling a thrown exception object in such a type-erased way is what std::exception_ptr
exists for:
std::exception_ptr ex;
for (...) {
try {
// code that could throw
} catch (...) {
ex = std::current_exception();
}
}
if(ex) // Only evaluates to true if a thrown exception was assigned to it.
std::rethrow_exception(ex);
All the lifetime concerns related to the dynamic type of the exception object are handled by the standard library. You can think of ex
as a reference counted handle to the exception object, allowing you to hoist it out of the try-catch block.
This follows the approach you laid out in your post and then confirmed in a comment, that the last exception thrown is the one that gets re-thrown.
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