Error Handling Patterns
Compose optional and expected.
Error Handling Patterns is a free C++ Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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";
}Optional to Expected
Convert a missing optional into a described error when the caller needs a reason.
#include <expected>
#include <optional>
#include <string>
std::expected<int, std::string> require(std::optional<int> o) {
if (o) return *o;
return std::unexpected("value missing");
}
int main() {}Chaining with value_or
When several lookups feed into one result, value_or lets you supply defaults inline without nested ifs.
#include <iostream>
#include <optional>
int setting(std::optional<int> user, int fallback) {
return user.value_or(fallback);
}
int main() {
std::cout << setting(std::nullopt, 42) << "\n";
}Propagating Errors Upward
With std::expected, a function can inspect a sub-call and forward its error unchanged, building an error pipeline.
#include <expected>
#include <string>
using R = std::expected<int, std::string>;
R step1(bool ok) { return ok ? R(2) : R(std::unexpected("step1 failed")); }
R run(bool ok) {
auto r = step1(ok);
if (!r) return std::unexpected(r.error());
return *r * 10;
}
int main() {}Monadic and_then
C++23 and_then chains operations that each return an optional or expected, short-circuiting on the first failure, no manual if cascade.
transform for Mapping
transform applies a plain function to the success value and leaves errors or emptiness untouched, mapping the happy path only.
or_else for Recovery
or_else runs a fallback that can supply a replacement value or alternative error when the original is empty or failed.
Choosing Between Them
Use optional when absence needs no explanation (a cache miss). Use expected when the caller must distinguish failure reasons (parse vs permission errors).
Avoid Mixed Sentinels
Do not mix old-style error codes with optional/expected in one API. Pick one consistent strategy so callers handle failures uniformly.
Keep Errors Typed
Prefer an enum or small struct for the error type instead of bare strings when failures are checked programmatically; strings are best for human-facing messages.
Quick Check
Check your understanding of error-handling patterns.
Recap
You learned error-handling patterns:
- Early-return on empty/error keeps code flat.
- Convert optional to expected when a reason is needed.
- Compose with
and_then,transform,or_else(C++23). - Stay consistent; avoid mixing sentinels with optional/expected.
Frequently asked questions
Is the “Error Handling Patterns” lesson free?
Yes — the full text of “Error Handling Patterns” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.
What will I learn in “Error Handling Patterns”?
Compose optional and expected. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C++ Academy?
No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Error Handling Patterns” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C++ Academy lesson?
Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Representing Absence with optional
- Accessing optional Values
- std::expected Basics
- Error Handling Patterns