Modern C++ • C++20 baseline
Choosing Between Exceptions, optional, and Expected Results
Represent expected absence and failure in a way that callers can handle deliberately.
Use optional when a value may simply be absent. Use exceptions when an operation fails in a way that ordinary callers cannot reasonably ignore. C++23 adds std::expected for a value-or-error return type; use it only when the target compiler and library support it, or use a project-approved result type on a C++20 baseline.
Key points
- Do not encode failure with a valid-looking magic value.
- C++20 has optional and variant; std::expected is a C++23 facility.
Example
#include <cstddef>
#include <optional>
#include <string>
std::optional<int> parse_small_number(const std::string& text) {
if (text == "one") {
return 1;
}
return std::nullopt;
}
What to expect
The function returns 1 for “one” and an empty optional for unsupported input.
Practice exercise
Design an expected-style return for a parser with separate “empty input” and “invalid number” errors.
Key idea: Select an error representation that matches how common and recoverable the failure is.