Modern Error Handling
Modern Error Handling
Use optional, variant, expected, exceptions, and result-oriented APIs deliberately.
Modern Error Handling
Use optional, variant, expected, exceptions, and result-oriented APIs deliberately.
std::optional<T> when absence is normal and there is no extra error detail.std::expected<T, E> when callers should handle a typed error locally.std::variant<Ts...> when a result can be one of several valid shapes.std::optionalstd::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::expectedenum 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::variantusing ConfigValue = std::variant<int, bool, std::string>;
Visit a variant when the set of alternatives is fixed and meaningful.
expected randomly in the same layer.[[nodiscard]].optional: missing value is normal.expected: caller should branch on success vs error.variant: multiple valid shapes.