public member function
<future>

std::promise::set_exception

void set_exception (exception_ptr p);
Set exception
Stores the exception pointer p in the shared state, which becomes ready.

If a future object that is associated to the same shared state is currently waiting on a call to future::get, it unblocks and throws the exception object pointed by p.

Parameters

p
An exception_ptr object.
exception_ptr is a smart pointer type designed to reference exception objects.

Return value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// promise::set_exception
#include <iostream>       // std::cin, std::cout, std::ios
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <exception>      // std::exception, std::current_exception

void get_int (std::promise<int>& prom) {
  int x;
  std::cout << "Please, enter an integer value: ";
  std::cin.exceptions (std::ios::failbit);   // throw on failbit
  try {
    std::cin >> x;                           // sets failbit if input is not int
    prom.set_value(x);
  }
  catch (std::exception&) {
    prom.set_exception(std::current_exception());
  }
}

void print_int (std::future<int>& fut) {
  try {
    int x = fut.get();
    std::cout << "value: " << x << '\n';
  }
  catch (std::exception& e) {
    std::cout << "[exception caught: " << e.what() << "]\n";
  }
}

int main ()
{
  std::promise<int> prom;
  std::future<int> fut = prom.get_future();

  std::thread th1 (print_int, std::ref(fut));
  std::thread th2 (get_int, std::ref(prom));

  th1.join();
  th2.join();
  return 0;
}


Possible output:

Please enter an integer value: boogey!
[exception caught: ios_base::failbit caught]

Data races

The promise object is modified.
The shared state is modified as an atomic operation (causing no data races).

Exception safety

Basic guarantee: if an exception is thrown, the promise object is in a valid state.

This member function throws an exception on the following conditions:
exception typeerror conditiondescription
future_errorfuture_errc::no_stateThe object has no shared state (it was moved-from)
future_errorfuture_errc::promise_already_satisfiedThe shared state already has a stored value or exception
Depending on the library implementation, this member function may also throw exceptions to report other situations.

See also