C++ · Module 15 · Lesson 41 min read

Alternatives: Error Codes, optional & expected

Options for reporting failure

ApproachGood forDrawbacks
Exceptionsrare, serious errors far from the handlerhidden control flow; some projects disable them
bool / error code returnsimple yes/no, C APIseasy to ignore; result needs an out-parameter
std::optional<T>"value or nothing" (not found, empty)no reason given
std::expected<T, E> (C++23) ✅"value or a specific error"newer standard
std::error_codeOS/library error categoriesverbose

std::expected<T, E> (<expected>)

scss
std::expected<double, std::string> parse_amount(std::string_view s) {
    if (s.empty()) return std::unexpected("empty input");
    ...
    return value;
}

auto r = parse_amount("12.5");
if (r) use(*r);                 // has a value
else   show(r.error());         // has an error
r.value_or(0);
  • has_value(), *r, r.value() (throws bad_expected_access if it's an error), r.error()
  • Monadic chaining (C++23): and_then, transform, or_else, transform_error
scss
auto total = parse_amount(input)
    .and_then(validate_positive)
    .transform(add_vat);

Error enums

A small enum class of error reasons works well as E: enum class ParseError { Empty, NotANumber, Negative };

[[nodiscard]]

Mark functions that return results/errors [[nodiscard]] so ignoring them triggers a warning.

Choosing ✅

  • Input validation, parsing, lookups → optional / expected
  • Constructor failures, broken invariants, resource failures deep in a call stack → exceptions
  • Performance-critical or no-exception environments (embedded, games) → expected / error codes
  • Be consistent within one module

Compiler support

std::expected needs -std=c++23 (GCC 12+, Clang 16+ with libc++/libstdc++, MSVC 2022).

Example

C++
#include <charconv>
#include <expected>
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
#include <vector>

enum class ParseError { Empty, NotANumber, Negative };

std::string_view describe(ParseError e) {
    switch (e) {
        case ParseError::Empty: return "input is empty";
        case ParseError::NotANumber: return "not a number";
        case ParseError::Negative: return "amount must be positive";
    }
    return "unknown";
}

[[nodiscard]] std::expected<double, ParseError> parse_amount(std::string_view s) {
    if (s.empty()) return std::unexpected(ParseError::Empty);
    double value{};
    auto [end, ec] = std::from_chars(s.data(), s.data() + s.size(), value);
    if (ec != std::errc{} || end != s.data() + s.size()) return std::unexpected(ParseError::NotANumber);
    return value;
}

std::expected<double, ParseError> require_positive(double x) {
    if (x <= 0) return std::unexpected(ParseError::Negative);
    return x;
}

std::optional<std::string> find_category(const std::vector<std::string>& cats, char first_letter) {
    for (const auto& c : cats) if (c[0] == first_letter) return c;
    return std::nullopt;
}

int main() {
    for (std::string_view input : { "1500", "", "12abc", "-40", "99.9" }) {
        auto result = parse_amount(input)
                          .and_then(require_positive)                    // chain another check
                          .transform([](double x) { return x * 1.13; }); // only runs on success
        std::cout << '"' << input << "\" -> ";
        if (result) std::cout << "with VAT " << *result << '\n';
        else std::cout << "error: " << describe(result.error()) << '\n';
    }

    auto r = parse_amount("oops");
    std::cout << "value_or(0) for \"oops\": " << r.value_or(0) << '\n';
    try {
        std::cout << r.value() << '\n';
    } catch (const std::bad_expected_access<ParseError>& e) {
        std::cout << "value() threw: " << describe(e.error()) << '\n';
    }

    std::vector<std::string> cats = { "Food", "Rent", "Travel" };
    std::cout << "category starting with R: " << find_category(cats, 'R').value_or("none")
              << ", with Z: " << find_category(cats, 'Z').value_or("none") << '\n';
    return 0;
}

/* Output:
"1500" -> with VAT 1695
"" -> error: input is empty
"12abc" -> error: not a number
"-40" -> error: amount must be positive
"99.9" -> with VAT 112.887
value_or(0) for "oops": 0
value() threw: not a number
category starting with R: Rent, with Z: none
*/