Errors and contracts #
The C legacy #
C reports failure via integer return codes and the global variable errno. Callers must remember to test each result, otherwise silent bugs arise.
C++ adds mechanisms that make ignoring failures harder: the type system can encode error states, and the [[nodiscard]] attribute warns when a result is discarded, ensuring the intent to handle errors is visible.
Exceptions and unwinding #
C++ supports throw, try, and catch. A throw aborts the current function, triggers stack unwinding, and destroys each local object in reverse order, allowing RAII objects to release resources automatically and preventing leaks.
Exceptions apply when the failure cannot be repaired at the call site, such as out‑of‑memory, corrupted files, or invalid user input.
The dividing line between exceptions and expected is the frequency and the locality of the failure. A parse error is routine: the caller expects it, handles it, and moves on, so it travels as an expected value. An out-of-memory error is rare and crosses abstraction boundaries: no individual caller can fix it, so it travels as an exception and unwinds to the nearest handler. Mixing the two is a smell: if every caller wraps a function in a try/catch, the failure is routine and belongs in an expected.
Modern ABIs place the exception handling code on the cold path only. The common case executes without extra branches or hidden calls. The claim that exceptions add overhead no longer applies to the common case. When exceptions are disabled with -fno-exceptions, the compiler omits unwind tables, reducing binary size and improving load time.
noexcept #
The specifier noexcept promises that a function will not throw. If a noexcept function does throw, the runtime calls std::terminate.
noexcept is a contract, not a hint. The compiler uses it to make decisions: a std::vector will move elements during reallocation only if the move constructor is noexcept, and the optimizer can elide exception-handling machinery around a noexcept call. Breaking the contract by throwing from a noexcept function calls std::terminate, which is a hard stop. The specifier is therefore a promise you make when you can guarantee it, not a wish.
Marking move constructors as noexcept enables the standard library to move objects during vector growth without a fallback copy. The optimizer can also inline the call more aggressively. noexcept functions can be inlined without hidden control flow. The optimizer gains full visibility of the call graph.
A conditional noexcept(...) expression makes the promise precise: the function is noexcept only when every operation it calls is noexcept itself, so the guarantee evolves with the implementation.
{{#include ../../examples/ch09/throw_noexcept.cpp}}
The program prints a marker that shows the noexcept move was used.
std::expected<T, E> #
std::expected<T, E> represents either a value of type T or an error of type E. It is a typed, non‑throwing alternative for functions that can fail.
Compare to std::optional<T>: optional conveys only presence or absence. expected also conveys an error description.
Contrast to exceptions: expected returns an object that the caller must inspect. Control flow stays explicit in the source.
{{#include ../../examples/ch09/expected_parse.cpp}}
The demo parses an integer from a string view. On success it prints the value. On error it prints the error string.
std::expected composes. A function that calls another fallible function can pass the error upward with a single expression. .and_then chains success and .or_else handles failure. This keeps the error path linear and avoids the nested if/else pyramids that error-code APIs produce. The type carries both the value and the error, so the compiler tracks whether the result has been checked.
The monadic interface is what makes expected scale beyond two calls. Without it, a function that calls three fallible operations in a row needs three nested if statements, each checking and forwarding. With .and_then, the same logic is a single chained expression that reads left to right. The error short-circuits: the first failure skips the rest of the chain and returns the error to the caller. This is the same shape as Rust's ? operator, expressed as method calls.
Contracts (C++26) #
C++26 adds four contract attributes that can be placed on statements or function signatures.
[[assert]]: a debugging check that aborts if the condition is false.[[assume]]: a promise to the optimizer that the condition is always true.[[expects]]: a precondition that must hold when the function is entered.[[ensures]]: a postcondition that must hold when the function returns.
The syntax is inline and looks like a standard attribute.
// Illustrative stub: does not compile on all compilers
[[expects: a > 0]]
[[ensures: result >= a ]]
int factorial(int a) {
[[assert: a >= 0]];
int result = 1;
for (int i = 2; i <= a; ++i) result *= i;
return result;
}
Compilers differ in support. GCC 16 implements contracts behind a flag. Clang does not yet implement the feature. The snippet therefore serves only as an illustration.
Contracts encode the same invariants that the earlier chapters express with RAII and lifetimes. When the compiler cannot prove an invariant, a contract can document it and trigger a runtime check in debug builds.
Contracts and assertions serve different audiences. An assertion checks an internal invariant that the function itself controls. A precondition checks a contract between the caller and the callee: the caller guarantees the condition, and the callee relies on it. A postcondition runs the contract in reverse: the callee guarantees the condition, and the caller relies on it. The four attributes let you state who is responsible for what, which a plain assert cannot express.
The violation handler decides what happens when a contract breaks. The implementation can ignore the violation, log it, abort, or call a user-defined handler. The default is observe, which logs and continues. The enforce mode aborts. This flexibility lets a project ship with contracts in debug builds and strip them in release, or keep them on in production with a handler that reports to a monitoring service.
Historical perspective on error handling #
Early C programs used integer return codes and errno as the sole mechanism for reporting failure. The programmer had to check each call manually, and forgetting a check produced silent corruption. C++98 introduced exceptions as a language feature that separates error propagation from the normal control flow. The first implementations used a table‑based “zero‑cost” model that stored unwind information in the object file. Compilers later added the ability to mark functions noexcept. This ability let the optimizer elide unwind handling for guaranteed‑non‑throwing code. C++23 added std::expected as a standard library type that returns either a value or an error object. Failure became an explicit part of the type system. C++26 formalizes contracts, completing the error‑handling toolbox.
Choosing a strategy #
| Situation | Recommended tool |
|---|---|
| Failure cannot be recovered locally. | Throw an exception. |
| Failure is routine and the caller must handle it inline. | Return std::expected. |
| Absence carries no extra information. | Return std::optional. |
| Invariant must never be violated. | Use a contract attribute. |
| Function is guaranteed not to throw. | Mark noexcept. |
The table is a decision tree, not a menu. Read the failure mode first, then pick the tool. A function that fails because the input is bad returns expected. A function that fails because the system ran out of memory throws. A function that cannot fail marks itself noexcept. A function that documents a contract uses an attribute. The four tools cover four failure modes, and the modes do not overlap.
Use the tool that matches the semantic intent and avoid mixing strategies without a clear reason. A library that mixes expected and exceptions forces the caller to hold two mental models. Choose a single default per module and deviate only when the failure profile demands it. For example, a parser returns expected because every call can fail, while a memory allocator throws because out‑of‑memory is rare and unrecoverable.
Impossible cases #
When the program reaches a state that the logic says cannot occur, the code can call one of the following.
std::abort(): terminates the process immediately.std::terminate(): ends the program after invoking the terminate handler.std::unreachable(): tells the compiler that this point is unreachable. Reaching it results in undefined behavior.
These calls are reserved for truly impossible branches such as a default case in a switch that covers every enum value.
std::unreachable is the strongest of the three. It tells the optimizer that the code path is dead, so the compiler can assume it never runs and use that fact to improve the surrounding code. If the assumption is wrong, the behaviour is undefined. Use it only after a construct that exhausts every case, such as a switch over a std::variant where the visitor covers every alternative. std::terminate is the safe fallback when the program is in a state you cannot reason about: it stops without running destructors, which avoids making things worse.
Try this #
Write a function
std::expected<double, std::string> divide(double a, double b);
The function returns an error string when b == 0. Then write a caller that handles both the value and the error.