Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::bad_optional_access — exception for empty optional access

std::bad_optional_access is the exception thrown by value() when std::optional contains no value. Distinguish this checked access from the * and -> operators, which require a value to be present.

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

Syntax

#include <optional>

try {
    opt.value();
} catch (const std::bad_optional_access& e) {
    // Handle access to an empty optional.
}

// C++23 member signature:
// const char* what() const noexcept override;

std::bad_optional_access is an exception class declared in <optional> that publicly derives from std::exception. Calling value() on an empty std::optional<T> throws this exception; merely creating an empty object is not an error.

Catch the exception by const std::bad_optional_access&. Its what() method returns a null-terminated diagnostic string whose contents are implementation-defined. Do not compare it with fixed text in portable tests.

The * and -> operators require a value to be present: they are not substitutes for value() that guarantee this exception. In C++23, using them on an empty object causes undefined behavior. If absence is expected, check has_value() or use the object in an if condition; value_or(fallback) returns a fallback value when the object is empty.

The example deliberately calls value() on an empty object, catches the exception, and then uses value_or(42). A fixed message keeps the output predictable. The supplied sources are a living working draft, not frozen C++23 wording; the constexpr shown there for what() is not treated here as a C++23 guarantee.

Examples

#include <iostream>
#include <optional>

int main() {
    std::optional<int> number;

    try {
        const int value = number.value();
        std::cout << value << '\n';
    } catch (const std::bad_optional_access&) {
        std::cout << "empty optional\n";
    }

    std::cout << number.value_or(42) << '\n';
}

Result

empty optional
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