Exception propagation and std::future

16,748

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.

Share:
16,748
Bukes
Author by

Bukes

Updated on June 21, 2022

Comments

  • Bukes
    Bukes almost 2 years

    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;
    }
    
  • Bukes
    Bukes over 11 years
    Gah! I'll buy this, but it is confusing - especially if the std::future created by std::async has a void result type. Calling get() for such a future feels weird.
  • GManNickG
    GManNickG over 11 years
    @Bukes: Heh I could see that. But don't think of future<T> as "a result of T", think of it as "the result of calculating T", which of course could be an exception.
  • PapaDiHatti
    PapaDiHatti almost 7 years
    @GManNickG what if function is returning void then don't you think it make sense to call wait() instead of get()
  • PapaDiHatti
    PapaDiHatti almost 7 years
    @GManNickG what if function is returning void then don't you think it make sense to call wait() instead of get()