Search⌘ K
AI Features

- Solution

Understand how to use C++ promises and futures to handle exceptions in multithreaded environments. Learn to catch, propagate, and manage errors safely while executing multiple tasks simultaneously to ensure reliable embedded programming.

We'll cover the following...

Solution

C++
// promiseFutureException.cpp
#include <exception>
#include <future>
#include <iostream>
#include <thread>
#include <utility>
struct Div{
void operator()(std::promise<int>&& intPromise, int a, int b){
try{
if ( b==0 ) throw std::runtime_error("illegal division by zero");
intPromise.set_value(a/b);
}
catch ( ...){
intPromise.set_exception(std::current_exception());
}
}
};
int main(){
std::cout << std::endl;
// define the promises
std::promise<int> divPromise;
// get the futures
std::future<int> divResult= divPromise.get_future();
// calculate the result in a separat thread
Div div;
std::thread divThread(div, std::move(divPromise), 20, 0);
// get the result
try{
std::cout << "20/0= " << divResult.get() << std::endl;
}
catch (std::runtime_error& e){
std::cout << e.what() << std::endl;
}
divThread.join();
std::cout << std::endl;
}

Explanation

  • The promise can send a value (line 13) or an exception (line 16). The exception in this case is the current exception std::current_exception().

  • When we divide by zero in line 33, it triggers the exception in line 12. ...