My understanding is that when an asynchronous operation throws an exception, it will be propagated back to a thread that calls std::future::get()
. However, when such a thread calls std::future::wait()
, the exception is not immediately propagated - it'll be thrown upon a subsequent call to std::future::get()
.
However, In such a scenario, what is supposed to happen to such an exception if the future object goes out of scope after a call to std::future::wait()
, but prior to a call to std::future::get()
?
For those interested, here is a simple example. In this case, the exception is silently handled by the thread/future package:
#include "stdafx.h"
#include <thread>
#include <future>
#include <iostream>
int32_t DoWork( int32_t i )
{
std::cout << "i == " << i << std::endl;
throw std::runtime_error( "DoWork test exception" );
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
auto f = std::async( DoWork, 5 );
try
{
//f.get(); // 1 - Exception does propagate.
f.wait(); // 2 - Exception does NOT propagate.
}
catch( std::exception& e )
{
std::cout << e.what() << std::endl;
return -1;
}
return 0;
}
std::future A future is an object that can retrieve a value from some provider object or function, properly synchronizing this access if in different threads. "Valid" futures are future objects associated to a shared state, and are constructed by calling one of the following functions: async. promise::get_future.
To catch an exception originating in thread X , you have to have the try - catch clause in thread X (for example, around everything in the thread function, similarly to what you already do in main ).
3) std::future is not CopyConstructible.
std::exception::whatReturns a null terminated character sequence that may be used to identify the exception. The particular representation pointed by the returned value is implementation-defined. As a virtual function, derived classes may redefine this function so that specific values are returned.
It is ignored and discarded, just like if you wait()
for a value but never get()
it.
wait()
simply says "block until the future is ready", be that ready with a value or exception. It's up to the caller to actually get()
the value (or exception). Usually you'll just use get()
, which waits anyway.
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