Home/C++/Errors, exceptions, and resource guarantees

Errors, exceptions, and resource guarantees

Error categories, stack unwinding and strong state guarantees

Use absence for an expected missing result, exceptions for a documented invalid request or failed operation, and a value type when callers need structured error detail. C++20 has optional and variant; std::expected is a later standard feature and is not assumed here. Do not use a valid value such as zero as an undocumented error sentinel.

cpp
std::optional<Int> find_balance(std::string_view id); // absent account is ordinary
// Invalid amounts throw std::invalid_argument before the account lookup.

Exceptions unwind stack frames, destroying fully constructed local owners. Catch by const reference to avoid slicing and unnecessary copies. A destructor normally must not allow an exception to escape. noexcept is a commitment: if an exception escapes it, the process terminates. It is not a request to ignore failures.

The basic guarantee preserves valid invariants and avoids resource leaks after failure. The strong guarantee leaves observable state unchanged. A no-throw guarantee promises no escaping exceptions. A function can provide the strong guarantee by constructing a candidate value and committing with a nonthrowing swap only after all validation and potentially failing transformation finishes.

cpp
auto candidate=current; // may allocate; current remains untouched
// mutate and validate candidate
current.swap(candidate); // commit after success

Validate-before-write is sufficient when all later operations cannot fail. It is insufficient if allocation, callbacks, or external work can throw halfway through mutation. Consider those failure points when claiming atomicity. The exercise's injected callback failure deliberately occurs after one candidate update. Catching the error without restoring live state would fail the contract. Copy-and-commit costs O(n) additional storage, an explicit tradeoff that can later be replaced by an undo log when workload evidence warrants it.

Put it into practice

Implement the exercise in a full-screen workspace, then run its tests.

Open practice
Next lessonIterators, algorithms, ranges, and invalidation