Handling exceptions
Exception propagation from the asynchronous task to the main thread is not supported when using std::async
. To enable exception propagation, we might need a promise object to store the exception that later can be accessed by the future returned when calling std::async
. But that promise object is not accessible or provided by std::async
.
One feasible way to achieve this is to use a std::packaged_task
object wrapping the asynchronous task. But if that is the case, we should directly use a packaged task as described in the previous chapter.
We could also use nested exceptions, available since C++11, by using std::nested_exception
, a polymorphic mixin class that can capture and store the current exception, allowing nested exceptions of arbitrary types. From a std::nested_exception
object, we can retrieve the stored exception by using the nested_ptr()
method or rethrow it by calling rethrow_nested()
.
To create a nested exception, we can throw an exception using...