Error handling in modern C++: optional, exceptions and result codes
When to return std::optional, when to throw, and when to return a result code, with examples. Plus [[nodiscard]], validating at the edges and keeping state consistent on failure.
C++ gives you several ways to report failure. Choosing well makes code easier to use correctly and harder to use wrongly.
Three tools, three situations
| Situation | Use |
|---|---|
| "No value" is a normal answer | std::optional<T> |
| Several distinct, expected outcomes | an enum class result code |
| A bug or broken precondition the caller can't fix | an exception |
std::optional for "maybe no value"
std::optional<char> letter_grade(int score) {
if (score < 0 || score > 100) return std::nullopt;
// ...
}The caller can't mistake "no grade" for a grade, unlike returning '?' or -1. Callers check with
if (grade) and read with *grade.
Result codes when the reason matters
When the caller needs to know why something was refused, return an enum:
enum class [[nodiscard]] Result { Ok, UnknownAccount, InvalidAmount, InsufficientFunds };
Result transfer(const std::string& from, const std::string& to, std::int64_t cents);[[nodiscard]] on the enum makes the compiler warn if anyone ignores a Result. That's how
the Coinbridge ledger makes sure a refused transfer never goes unnoticed.
Exceptions for bugs and broken contracts
if (line.quantity <= 0) {
throw std::invalid_argument("line " + std::to_string(i + 1) + ": quantity must be positive");
}An invalid invoice line means something upstream is broken; printing an invoice anyway would be worse than stopping. Make the message actionable: which line, what's wrong.
Keep state consistent when something fails
The most important rule is about state, not syntax: check everything first, change state last. If every check runs before any change, a refused operation can't leave things half-done:
if (!accounts.contains(from) || !accounts.contains(to)) return Result::UnknownAccount;
if (cents <= 0) return Result::InvalidAmount;
if (balance(from) < cents) return Result::InsufficientFunds;
// Only now: change both balances.For resources (files, locks, memory), let objects release them automatically, so an exception can't leak them; see RAII and smart pointers.
Validate at the edges
Validate input where it enters your system (parsing, constructors, public methods), so the core only ever sees valid data. Then most functions don't need error handling at all.
Questions and answers
- Should I use exceptions in C++?
- For errors the caller can't reasonably handle on the spot, like a broken invariant or an invalid argument that indicates a bug, yes. For expected outcomes, like a lookup that finds nothing or user input that doesn't parse, return a value instead.
- What does [[nodiscard]] do?
- It makes the compiler warn when a caller ignores the return value. Put it on result codes and functions whose result must be checked, so a refused transfer can't be silently ignored.
Practise it in a project
These projects put this guide to work, with tickets, tests and code review.
Coinbridge Credit Union
Account ledger for Coinbridge
Build the ledger behind Coinbridge's accounts: deposits, withdrawals, all-or-nothing transfers, reversals and statements with running balances.
- invariants
- atomic operations
- audit trails
- result codes
Ledgerly
Invoice totals for Ledgerly
Read amounts, compute net, VAT and gross totals to the cent, and never lose a cent to floating point.
- integer arithmetic
- rounding
- parsing
- exceptions
Brightpath Academy
A gradebook for Brightpath Academy
Give Brightpath's teachers letter grades, averages and a class ranking, instead of a spreadsheet full of formulas.
- conditionals
- classes
- std::map
- sorting
Read next
- Code review checklist for junior developers
What senior engineers look for in a code review, as a practical checklist: correctness, edge cases, tests, naming, structure and performance, with C++-specific points.