Core · Module 8 · Lesson 5 of 5
C++23 std::expected: Returning Values or Errors
Use std::expected to return a successful value or a typed failure, compose operations, and choose it deliberately alongside exceptions and optional.
By the end you can
- Model recoverable failures with std::expected<T, E> and a specific error type
- Check and propagate expected values without reading an absent result
- Choose between expected, optional, error codes and exceptions for an API
Builds on Project: Failing Library Operations Cleanly, Modern Standard-Library Tools: optional, variant, span and ranges.
01 · A question first
A parser can return a number or a useful reason that the input was rejected. Returning a magic value such as -1 loses detail, while throwing for every ordinary invalid row can make a batch importer awkward. How can the return type make both outcomes explicit?
Make a guess before you read on.
02 · The idea
Members only
Unlock the full lesson
This lesson is part of the membership. Join to read it in full, along with every other premium deep dive.
What's inside
- Make both outcomes part of the return type
- Give errors stable names
- Propagate, transform and recover
- Choose the failure vocabulary deliberately
- Test both alternatives and the boundaries
Something wrong with this lesson? Report a problem