Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ catch exception in a loop and rethrow _after_ the loop finishes?

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:

  1. Copy ex to an ExceptionObj value. Problem: doesn't scale well at all when ex has subclasses or more exceptions need to be handled.

  2. Have a clone method in ExceptionObj that returns a copy on the heap. Problem: doesn't work for third party exceptions.

like image 482
misev Avatar asked Dec 09 '18 11:12

misev


1 Answers

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.

like image 99
StoryTeller - Unslander Monica Avatar answered Sep 30 '22 13:09

StoryTeller - Unslander Monica