Lesson 5 of 9 · 26m
Errors Without Theater: Exceptions, optional, and expected
Pick error mechanisms based on failure distance and recovery semantics, use RAII to keep exception safety safe, and expose honest failure types at boundaries.
Teams love arguing about exceptions as if there is one correct religion. In practice the question is simpler: who can handle this failure, and how far is the error allowed to travel before someone can? Parser errors in a hot packet loop are expected control flow. Corrupt internal state in a constructor is often exceptional. The maintainable systems use both mechanisms deliberately instead of pretending one size fits every failure.
Exceptions are for non-local failure
Constructors cannot return error codes. Operators and destructors are awkward places for out-parameters. Exceptions solve non-local failure while RAII preserves correctness during unwinding:
Database::Database(const Config& cfg)
: connection_(open_connection(cfg)) {
if (!connection_.valid()) {
throw std::runtime_error("database connection rejected");
}
}If this constructor throws, fully constructed members are destroyed in reverse order. Because resources are owned by RAII types, failure does not leak halfway-open state. This is why exceptions and RAII are not competing styles; they are designed to work together.
Exception safety has levels. The strong guarantee means the operation either succeeds or leaves the object unchanged. Copy-and-swap remains a practical pattern:
Config& operator=(const Config& other) {
Config copy(other);
swap(copy);
return *this;
}Expected failures deserve values
C++23 gives us std::expected, which states failure in the type system instead of using sentinel values or output parameters:
enum class ParseError { empty_input, invalid_header, trailing_bytes };
std::expected<Header, ParseError> parse_header(std::string_view input) {
if (input.empty()) return std::unexpected(ParseError::empty_input);
// ...
}Use it when immediate callers normally inspect or recover from failure. It is clearer than optional plus a global errno imitation, and unlike exceptions it makes the failure path visible in the signature. On older standards, tl::expected and project-local equivalents fill the same role.
std::optional means absence, not failure. std::optional<User> can represent "no user found." It should not silently mean "database exploded."
noexcept is a contract, not decoration
Mark operations noexcept only when they truly cannot throw or when throwing is unrecoverable by design. Move constructors, swap operations, and destructors are central because containers and cleanup paths rely on them.
void swap(Header& other) noexcept {
using std::swap;
swap(fields_, other.fields_);
}If a noexcept function throws, std::terminate is the result. That may be correct for invariant collapse, but it is not a gentle error-reporting mechanism.
Error boundaries need translation
Low-level error codes should not leak through every layer. Translate at architectural boundaries:
syscall errno -> narrow filesystem error type
library error enum -> domain failure
domain failure -> HTTP response, CLI exit code, or telemetryPreserve cause in logs and error context. A terse failed at the top is operationally useless; a raw ECONNRESET in a domain API is abstraction inversion.
Field notes
- Catch by
const std::exception&unless you have a narrower type; catching by value slices. - Do not use exceptions for routine parse rejection in extremely hot paths if profiling shows cost and the failure is expected control flow.
- Error codes without context rot quickly; include operation, object identity, and category at the boundary.
- Never report success through
optionalemptiness if callers need to distinguish not-found, invalid-input, permission-denied, and backend failure.
Was this lesson helpful?