Modern Error Handling

Modern Error Handling

Use optional, variant, expected, exceptions, and result-oriented APIs deliberately.

Modern Error Handling

Choose the right tool

std::optional

std::optional<int> find_id(std::string_view name);

if (auto id = find_id("ada")) {
    std::cout << *id << '\n';
}

Use it for "maybe there is a value". Do not overload it with detailed failure reasons.

std::expected

enum class ParseError { invalid_digit, overflow };

std::expected<int, ParseError> parse_port(std::string_view text);

std::expected keeps the success path explicit and makes error propagation testable.

std::variant

using ConfigValue = std::variant<int, bool, std::string>;

Visit a variant when the set of alternatives is fixed and meaningful.

Practical guidance

Quick selection rules