std::futuremyFuture = std::async(std::launch::async, [](){ return 42; }); // Wait for the future to complete myFuture.wait(); if (myFuture.isFailed()) { std::cout << "Future failed!" << std::endl; } else { std::cout << "Future succeeded! Result: " << myFuture.get() << std::endl; }
std::futureIn this example, we create a future object that will execute a lambda function asynchronously, which will throw a "runtime_error" exception. We then wait for the future object to complete and check whether it has failed using the "isFailed" function. Since the future object has failed, we retrieve the exception using the "get" function within a try-catch block and print the error message to the console. The "Future" class and its associated functions are part of the C++ standard library.myFuture = std::async(std::launch::async, [](){ throw std::runtime_error("Oops!"); }); // Wait for the future to complete myFuture.wait(); if (myFuture.isFailed()) { try { myFuture.get(); } catch (const std::exception& e) { std::cout << "Future failed with exception: " << e.what() << std::endl; } }