function
<exception>
std::current_exception
exception_ptr current_exception() noexcept;
Get smart pointer to current exception
Returns an exception_ptr object that points to the currently handled exception, or to a copy of it.
If no exception is being handled, the function returns a null-pointer value.
exception_ptr is a shared smart pointer type: The pointed exception is guaranteed to remain valid for as long as at least one exception_ptr points to it, potentially extending the lifetime of the pointed exception object beyond its scope or across threads. See exception_ptr for more info.
This function throws no exceptions, but if the function is implemented as returning a pointer to a copy of the currently handled exception, it may return a pointer to a different exception if it fails to allocate storage (bad_alloc) or if the copying process fails (it returns the thrown exception or bad_exception, if possible; or some other unspecified value, otherwise).
Return value
An exception_ptr object pointing to the currently handled exception, or some other exception if the internal process of the function would raise a new 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
Whether the function returns an object that points to the currently handled exception or to a copy of it depends on the particular library implementation.
Exception safety
No-throw guarantee: this function throws no exceptions. Instead, this function uses its return value to signal exceptions thrown during its internal operation.