Learning Hub Search Ctrl K

Modern C++ › C++23

std::expected

Error handling without exceptions.

Since C++23 intermediate #expected#error-handling#monadic-operations#and_then#unexpected

Explanation

std::expected<T, E> (header <expected>) is a return type that holds either a value of type T or an error of type E. It makes failure part of the function’s signature, without exceptions and without sentinel values or output parameters. Think of it as optional that also explains why there is no value, or as a two-alternative variant with a friendly API.

Create: return a value (return 42;) for success or std::unexpected(err) for failure.

Inspect:

  • if (r) / r.has_value(): success?
  • *r, r.value(): the value (value() throws std::bad_expected_access<E> on error)
  • r.error(): the error
  • r.value_or(default)

Monadic operations (C++23) chain steps and stop at the first error:

Operation Does
r.and_then(f) on success call f(value) (which itself returns an expected)
r.transform(f) on success map the value, wrapping the result
r.or_else(f) on error call f(error) (recovery)
r.transform_error(f) map the error type

Example

#include <charconv>
#include <expected>
#include <iostream>
#include <string>
#include <string_view>

enum class ParseError { Empty, NotANumber, OutOfRange };

std::string_view toText(ParseError e) {
    switch (e) {
        case ParseError::Empty:      return "empty input";
        case ParseError::NotANumber: return "not a number";
        case ParseError::OutOfRange: return "out of range";
    }
    return "?";
}

std::expected<int, ParseError> parseInt(std::string_view s) {
    if (s.empty()) return std::unexpected(ParseError::Empty);
    int value = 0;
    auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value);
    if (ec == std::errc::result_out_of_range) return std::unexpected(ParseError::OutOfRange);
    if (ec != std::errc{} || ptr != s.data() + s.size()) return std::unexpected(ParseError::NotANumber);
    return value;
}

std::expected<int, ParseError> checkPositive(int n) {
    if (n <= 0) return std::unexpected(ParseError::OutOfRange);
    return n;
}

int main() {
    for (std::string_view input : {"42", "", "12x", "-5", "99999999999"}) {
        auto r = parseInt(input)
                     .and_then(checkPositive)                       // runs only on success
                     .transform([](int n) { return n * 2; });       // maps the value
        if (r) std::cout << input << " -> " << *r << "\n";
        else   std::cout << "'" << input << "' failed: " << toText(r.error()) << "\n";
    }

    std::cout << parseInt("oops").value_or(-1) << "\n";             // -1
    auto recovered = parseInt("oops").or_else([](ParseError) -> std::expected<int, ParseError> { return 0; });
    std::cout << *recovered << "\n";                                // 0
    return 0;
}

Common pitfalls

  • *r on an error is undefined behavior; r.value() throws. Check first.
  • std::expected<void, E> is allowed for operations that only succeed or fail.
  • If T and E are the same type, return via std::unexpected(...) explicitly to avoid confusion.
  • Using expected for truly exceptional conditions (out of memory) just moves the burden to every caller; reserve it for expected failures.
  • It doesn’t propagate automatically: C++ has no ? operator, so you write if (!r) return std::unexpected(r.error()); or use and_then.
  • Compiler support: MSVC 19.33+, GCC 12+, Clang 16+ (monadic operations a bit later).

Legacy vs modern

// C++98: sentinel / output parameter / errno
bool parseInt(const std::string& s, int& out);        // error reason lost
// C++98..20: exceptions
int parseInt(const std::string& s);                   // throws; cost and control flow are hidden
// C++17: std::optional<int>   // no reason for failure
// C++23: std::expected<int, ParseError>

See Exceptions for the traditional approach, and optional for the simpler “maybe a value” case.

Exercises

1. When would you choose std::optional over std::expected?

When “no value” is a normal, self-explanatory outcome (lookup miss) and callers don’t need a reason. Use expected when callers must know or act on why it failed.