C++ Quiz145 of 173
Difficulty:
⬅️ Prev: 296Quiz ID: 297Next: 298 ➡️

According to the C++23 standard, what is the output of this program?

#include <future>
#include <iostream>

int main()
{
    auto f = std::async(std::launch::async, [](){ throw 0; });
    try {
        f.wait();
    } catch (...)
    {
        std::cout << 1;
    }
    std::cout << 2;
}
Hint

f.get() throws the stored exception, if any. Here we call f.wait().

Reveal answer

2

Explanation

wait does not throw exceptions stored in the shared state.

§[futures.unique.future]¶21:

void wait() const;

Effects: Blocks until the shared state is ready.

To get at the exception, you have to use get. §[futures.unique.future]¶19:

R future::get();
R& future<R&>::get();
void future<void>::get();

Throws: the stored exception, if an exception was stored in the shared state.

So there's no exception thrown, the catch block is never entered, and the program only prints 2.

⬅️ Prev: 296Quiz ID: 297Next: 298 ➡️