Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::current_exception — retain the handled exception

std::current_exception from <exception> returns a std::exception_ptr referring to the currently handled exception or a copy. It lets you retain an exception and rethrow it later; with no handled exception, it returns a null value.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <exception>
std::exception_ptr std::current_exception() noexcept;

std::current_exception() from <exception> captures the currently handled exception, usually inside catch. It returns a std::exception_ptr referring to that exception or a copy. When no exception is being handled, the result is null: the function does not keep an error history.

The retained object remains valid at least while a referring std::exception_ptr exists, even after catch ends. To throw the exception later, use std::rethrow_exception(saved). Check if (saved) first: that function requires a non-null argument.

noexcept means capture itself does not throw to its caller. However, failed allocation can retain std::bad_alloc; failed copying can retain the exception thrown by copying, or std::bad_exception. Do not assume two successive calls refer to the same object either.

The example checks the null result before exception handling, then retains 42 and rethrows it after leaving catch. The code targets C++23; the supplied sources are a rolling working draft, not a frozen C++23 publication.

Examples

#include <exception>
#include <iostream>

int main() {
    std::cout << std::boolalpha << !std::current_exception() << '\n';

    std::exception_ptr saved;
    try {
        throw 42;
    } catch (...) {
        saved = std::current_exception();
    }

    if (saved) {
        try {
            std::rethrow_exception(saved);
        } catch (int value) {
            std::cout << value << '\n';
        } catch (...) {
            std::cout << "capture or rethrow failed\n";
        }
    }
}

Result

true
42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources