FrozenHeart
FrozenHeart

Reputation: 20736

What happens to exceptions thrown from functions launched via std::async

What happens to exceptions thrown from functions launched via std::async?

#include <future>
#include <iostream>
#include <stdexcept>

void foo()
{
  std::cout << "foo()" << std::endl;
  throw std::runtime_error("Error");
}

int main()
{
  try
  {
    std::cout << "1" << std::endl;
    auto f = std::async(std::launch::async, foo);
    f.get();
    std::cout << "2" << std::endl;
  }
  catch (const std::exception& ex)
  {
    std::cerr << ex.what() << std::endl;
  }
}

MSVC gives me the following output:

1
foo()
Error

Is it right that such exceptions will be caught outside the function by calling the get function?

Upvotes: 3

Views: 204

Answers (1)

Barry
Barry

Reputation: 302748

From cppreference:

[...] if the function f returns a value or throws an exception, it is stored in the shared state accessible through the std::future that async returns to the caller.

And in the reference about std::future::get():

If an exception was stored in the shared state referenced by the future (e.g. via a call to std::promise::set_exception()) then that exception will be thrown.

So yes, if your function throws an exception, that exception is basically deferred into the future and rethrown on get().

Upvotes: 10

Related Questions