Error Handling Patterns
Compose optional and expected.
Two Tools, One Goal
std::optional and std::expected both replace error-prone sentinels. This lesson shows patterns for combining and composing them cleanly.
Early Return on Empty
A simple, readable pattern: check the optional, and bail out early if it is empty before continuing.
#include <iostream>
#include <optional>
std::optional<int> parse(bool ok) { return ok ? std::optional<int>(5) : std::nullopt; }
int main() {
auto v = parse(true);
if (!v) { std::cout << "no value\n"; return 0; }
std::cout << *v + 1 << "\n";
}All lessons in this course
- Representing Absence with optional
- Accessing optional Values
- std::expected Basics
- Error Handling Patterns