skip to content

For a new C++ library's error-return convention, when should its API return std::expected rather than throw exceptions or return error codes?

level: principalimportance: should knowfreq 32%

answer

  1. how often the failure happens
  2. how far the handler is
  3. constructors cannot return one
  4. the consumers' minimum standard
  5. builds with exceptions disabled

basics

~10 s

Return std::expected for failures a direct caller routinely handles, such as parse or validation errors, and where exceptions are disabled; throw for rare failures handled far away and in constructors; std::expected requires C++23 consumers.

solid answer

~50 s

I decide per failure class, not per library. **`std::expected`** fits failures that are part of normal operation and handled by the immediate caller: parsing a config value, validating input, a lookup that can fail with a reason. It makes the failure visible in the signature, costs a branch instead of an unwind, and works where exceptions are disabled. **Exceptions** fit rare failures handled many frames up, and anything that cannot return a value: constructors, operators, callbacks through code that does not know your error type. **Error codes** through `std::error_code` remain the right choice when consumers are below C++23, cross a C ABI, or already use the `<filesystem>` style of dual throwing and `error_code&` overloads. The cost of `expected`: C++23 for consumers, noise in deep call chains, and an `E` that must be cheap and copyable. I write the rule down and keep one `E` per module so chains compose.

go deeper

for a junior

Know the three options exist: exceptions, error codes and std::expected since C++23, and that constructors can only report failure by throwing.

for a middle

Explain the cost model in plain terms: expected pays a check on every call, exceptions pay heavily only when thrown, and expected needs a C++23 compiler.

for a senior

Design the error type: one E per module, cheap to copy, mapped at boundaries with transform_error, and functions marked [[nodiscard]].

for a principal

Own the written rule: which failure classes use which mechanism, how it interacts with exception-free builds and consumer standards, and when the rule is revisited.

## The decision a lead owns A library's error-return convention is visible in every signature and hard to change once callers depend on it. C++ now offers three standard mechanisms: **exceptions**, **error codes** (an enum, or `std::error_code` from `<system_error>`), and, since C++23, **`std::expected<T, E>`**. There is no single right answer; the lead's job is to choose per failure class and write the rule down. The mechanics of throwing and catching are covered with exceptions; this answer is about when `expected` earns its place. ## Questions that drive the choice 1. **How often does the failure happen?** A malformed config value or a rejected request is routine; an out-of-memory or a corrupted invariant is not. Routine failures favour `expected`, because an exception's throw is expensive while its non-throwing path is close to free on common ABIs (a property of those implementations, not a promise of the standard). 2. **How far is the handler?** If the immediate caller decides (retry, default, report), `expected` puts the decision in its hands. If the only sensible handler is ten frames up, threading `expected` through every frame adds noise, and an exception carries the failure there without it. 3. **Can the function return anything at all?** Constructors, overloaded operators and destructors cannot return an `expected`. A type whose constructor can fail either throws, or hides construction behind a factory such as `static std::expected<Config, ConfigError> load(path)`. 4. **Are exceptions available?** Game engines and firmware often build with exceptions disabled. There `expected` is the only one of the three that keeps a typed error and a value together; how the standard library behaves without exceptions is a topic of its own. 5. **What standard do consumers compile with?** `std::expected` needs C++23 headers. A library whose users are on C++17 or C++20 cannot put it in public signatures, and must choose a backport or error codes. ## Comparing the options | Concern | `std::expected<T, E>` | Exceptions | Error codes | |---|---|---|---| | Visible in the signature | yes | no | yes, often as an out-parameter | | Cost on success | a flag check | near zero on common ABIs | a check | | Cost on failure | a return | an unwind, expensive | a return | | Works with exceptions off | yes | no | yes | | Constructors, operators | no | yes | awkward | | Forced handling | no: discarding compiles silently | uncaught means terminate | no | | Minimum standard | C++23 | any | any | ## Designing the error type A convention built on `expected` lives or dies by its `E`: - **One error type per module** (an enum, or a small struct with an enum and context) so that `and_then` chains compile; `and_then` mandates the same `error_type`. - **Cheap and copyable.** `expected::value()` mandates a copy-constructible `E`, since it throws `std::bad_expected_access<E>` holding a copy. - **Map at boundaries** with `transform_error` instead of leaking a lower layer's error type upward. - **`[[nodiscard]]` on returning functions**, because the standard does not require a warning when an `expected` is discarded. ## Mixed conventions are normal The standard library itself mixes them: `<filesystem>` offers most operations twice, once throwing `filesystem_error` and once taking a `std::error_code&` that receives the error instead (many of those overloads are `noexcept`, such as `exists(p, ec)`). A modern library can do the same with `expected`: return `expected` from the core, and let callers who prefer exceptions call `.value()`, which converts an error into `std::bad_expected_access<E>`. A defensible written rule for a new C++23 library might read: - Return `std::expected` for input, parse, validation and lookup failures the caller can act on. - Throw for broken invariants surfaced at runtime, resource exhaustion and constructor failure. - Use assertions or contracts, not either mechanism, for programming errors. - Never return a sentinel such as `-1` for a failure in a new API. ## What a principal answer adds The trade-offs reach beyond code: hiring and onboarding (exceptions are familiar), consistency with dependencies (mixing styles at every boundary costs adapters), binary size and determinism on constrained targets, and the upgrade path if consumers' minimum standard rises. The answer should show the decision is revisited when those facts change, not frozen.

  • A type's constructor can fail on bad input. How do you fit it into an expected-based convention?
    Constructors cannot return a value, so make the constructor private or infallible and add a static factory: `static std::expected<Config, ConfigError> parse(std::string_view text)`. The factory validates first and constructs only valid objects. Callers who prefer exceptions can still write `Config::parse(text).value()`.
  • How do you serve callers who want exceptions from a library whose core returns std::expected?
    Offer the `expected` API as primary and let those callers call `.value()`, which throws `std::bad_expected_access<E>` carrying the error. If a domain exception type is preferred, provide a thin throwing wrapper per entry point that converts `error()` into it. The core logic stays single-path either way.
  • Why should a module standardise on one error type before adopting and_then chains?
    `and_then` mandates that every step returns an `expected` with the same `error_type`. If each function invents its own enum, every chain needs `transform_error` adapters between steps, which cancels the readability chains were meant to buy. One module-level `E`, mapped once at the module boundary, keeps chains short.

  • std::expected should replace exceptions everywhere in a modern codebase
  • Exceptions are always slower than std::expected, even when nothing fails
  • A constructor can report failure by returning std::expected
  • Ignoring a returned std::expected produces a compiler error
  • std::expected works fine for consumers still on C++17

Assumes C++23 for std::expected; a library whose consumers build as C++17 or C++20 cannot expose it in public headers.