type
<exception>

std::exception_ptr

Exception pointer
Smart pointer type that can refer to exception objects.

It is a shared pointer-like type: The pointed exception is guaranteed to remain valid for as long as at least one exception_ptr points to it, potentially extending its lifetime beyond the scope of a catch statement or across threads.

Different libraries may implement this type differently, but it shall at least support the following operations without throwing:
  • Being default-constructed (acquiring a null-pointer value).
  • Being copied, including being copied a null-pointer value (or nullptr).
  • Being compared against another exception_ptr object (or nullptr) using either operator== or operator!=, where two null-pointers are always considered equivalent, and two non-null pointers are considered equivalent only if they refer to the same exception object.
  • Being contextually convertible to bool, as false if having null-pointer value, and as true otherwise.
  • Being swapped, and being destructed.

The type is also required to not be implicitly convertible to an arithmetic, enumeration, or pointer type.

Performing any other operation on the object (such as dereferencing it), if at all supported by the library implementation, causes undefined behavior.

Objects of this type are obtained by calling: current_exception, make_exception_ptr or nested_exception::nested_ptr, and can be accessed by rethrowing the pointed exception calling rethrow_exception.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// exception_ptr example
#include <iostream>       // std::cout
#include <exception>      // std::exception_ptr, std::current_exception, std::rethrow_exception
#include <stdexcept>      // std::logic_error

int main () {
  std::exception_ptr p;
  try {
     throw std::logic_error("some logic_error exception");   // throws
  } catch(const std::exception& e) {
     p = std::current_exception();
     std::cout << "exception caught, but continuing...\n";
  }

  std::cout << "(after exception)\n";

  try {
     std::rethrow_exception (p);
  } catch (const std::exception& e) {
     std::cout << "exception caught: " << e.what() << '\n';
  }
  return 0;
}

Output:

exception caught, but continuing...
(after exception)
exception caught: some logic_error exception


Data races

None of the operations portably supported by exception_ptr objects (as described above) access or modify the pointed exception object.

The class provides no additional synchronization guarantees to exception objects.

Exception safety

No-throw guarantee: none of the required operations throw exceptions.

Notice that performing any operation on the object that is not explicitly supported (as described above), causes undefined behavior.

See also