skip to content

Which exception-safety guarantee and noexcept policy should a C++ codebase require of its types and functions, and how would you justify it?

level: principalimportance: should knowfreq 40%

answer

  1. a floor, a target, a must
  2. noexcept is a forever promise
  3. narrow versus wide contracts
  4. enforce with traits and tests

basics

~20 s

A defensible policy: basic guarantee everywhere, strong where an operation is a natural commit point, nothrow for destructors, swap, release and cleanup. Mark noexcept only where failure is impossible by design and the promise can be kept forever.

solid answer

~40 s

I set three tiers. **Basic** is mandatory for every function, because anything less is a bug. **Strong** is required for operations callers treat as atomic, such as single insertions, configuration commits and assignment, and optional elsewhere, because staging copies for bulk operations costs real time. **Nothrow** is required for destructors, `swap`, deallocation and rollback paths, because the other guarantees are built from them. For `noexcept` I mark functions that cannot fail by design, and I avoid it on functions that allocate or that have preconditions we check with throwing assertions in tests, since a throw from a `noexcept` function is `std::terminate`. The standard library itself leaves `noexcept` off many functions and lets implementations add it. Enforcement: `static_assert` on type traits, clang's `-Wexceptions`, and fault-injection tests.

go deeper

for a junior

Know that teams set rules for which functions may be noexcept and which guarantee each kind of function must give.

for a middle

Explain why destructors, swap and cleanup must be nothrow and why a noexcept function that allocates turns std::bad_alloc into std::terminate.

for a senior

Apply the policy in review: spot functions whose documented guarantee their code does not deliver, and add fault-injection tests for strong operations.

for a principal

Choose and defend the tiers, the noexcept rule for narrow contracts and allocation, and the enforcement tooling, and revisit them as C++26 contracts arrive.

## The decision a lead owns Every C++ codebase ends up with an exception-safety policy, written or not. The question is whether the team chooses it or discovers it during an incident. A policy has two halves: **which guarantee** each kind of function must give, and **when `noexcept`** may be written. There is no single right answer, but there are defensible ones. ## Tiering the guarantees | Tier | Applies to | Reason | |---|---|---| | **Basic** (mandatory) | every function | a broken invariant poisons every later operation | | **Strong** (required where natural) | single-element inserts, configuration commits, assignment, anything callers treat as atomic | callers can retry or report without inspecting partial state | | **Strong** (optional) | bulk operations, batch imports | the cost is usually a full copy on the success path | | **Nothrow** (mandatory) | destructors, `swap`, deallocation, rollback and cleanup paths | the other guarantees are built from these | The trade-off to argue in an interview is the middle row. Requiring strong everywhere forces copies into hot paths; requiring it nowhere leaves callers guessing. Tying it to "operations a caller treats as a single action" gives a rule reviewers can apply. ## When to write `noexcept` `noexcept` is not just documentation: - It is part of the **function type** (C++17) and observable through the `noexcept` operator and traits such as `std::is_nothrow_swappable_v`, so callers and library templates choose code paths based on it. Removing it later can silently change those choices. - A violation is **`std::terminate`**, possibly without unwinding, never a recoverable error. Two common team rules: 1. **Mark only what cannot fail by design**: destructors (implicit anyway), `swap`, accessors, simple arithmetic, release functions. Do not mark functions that allocate, that call user callbacks, or that might grow a failure mode later. 2. **Leave `noexcept` off functions with preconditions** (narrow contracts) when the team checks preconditions with assertion handlers that throw in tests. A thrown assertion from a `noexcept` function terminates the test runner instead of failing one test. The standard library follows a similar line: many functions are specified without `noexcept`, and implementations are explicitly allowed to strengthen a non-virtual function's exception specification by adding one. C++26 adds a sharper version of rule 2. With contracts, a contract-violation handler invoked for a function's precondition or postcondition that exits via an exception calls `std::terminate` if the function is non-throwing, so a team that wants throwing violation handlers has to keep `noexcept` off functions with contract assertions. ## Generic code Templates should propagate rather than decide: a conditional `noexcept(noexcept(expr))` or a trait-based specification makes a wrapper exactly as non-throwing as what it wraps. A blanket `noexcept` on a template turns some instantiations into terminate traps. ## Enforcement - **Type traits in headers**: `static_assert(std::is_nothrow_destructible_v<T>)` and `static_assert(std::is_nothrow_swappable_v<T>)` for core types. - **Compiler warnings**: clang's `-Wexceptions` catches a direct `throw` inside a non-throwing function; keep it as an error. - **Fault-injection tests**: types whose copies throw on demand and allocators that fail after N allocations, run against every operation documented as strong. - **Review checklist**: every new public function states its guarantee in its comment. ## Rolling it out to an existing codebase A policy written after years of code needs a migration path rather than a flag day: 1. Start with the nothrow tier, since it is the cheapest to check: add `static_assert`s for destructors and `swap` of core types and fix what fails. 2. Turn on clang's `-Wexceptions` as an error and clear the findings. 3. Add fault-injection tests to the few operations callers treat as atomic, and fix any that are not strong. 4. Add the guarantee to the code review checklist for new public functions only, so the documentation grows with the code. ## Where reasonable teams differ - Some codebases build without exceptions at all and replace this policy with error codes; that choice belongs to restricted builds, not to this policy. - Some mark nearly everything `noexcept` for code size and accept that allocation failure terminates the process, a defensible stance for services that cannot run usefully after running out of memory. - Some require the strong guarantee for all public mutators to simplify reasoning, and pay for it in copies. The lead's job is to pick one, write it down, and make the tools enforce it.

  • Why is removing noexcept from a published function risky even if nothing throws yet?
    Callers may have used the `noexcept` operator or traits like `std::is_nothrow_swappable_v` to choose an implementation, and templates in other components may have specialised on it. Removing the specifier is an interface change that can silently switch those choices to slower or different paths. Adding `noexcept` later is the safer direction, which is why a cautious policy starts with fewer of them.
  • How does a policy handle allocation failure in noexcept functions?
    It has to decide explicitly. Either functions that allocate are never `noexcept`, so `std::bad_alloc` stays catchable, or the team accepts that running out of memory ends the process and marks freely for code size and speed. Both are defensible for different products; mixing them by accident is not.
  • Should every public mutator give the strong guarantee?
    Only if callers need atomicity there. For single-element operations it is usually cheap with a non-throwing undo; for bulk operations it often requires staging a full copy. A good policy requires strong for operations callers treat as one action and documents basic elsewhere, so the cost is paid only where it buys something.

  • Mark everything noexcept; it is free and makes code faster.
  • Every function must give the strong guarantee, whatever it costs.
  • noexcept can be removed later without affecting any caller.
  • A noexcept function's thrown exception still fails one unit test cleanly.

Assumes C++23 for the guarantee and noexcept rules (stable since C++17); the contract-violation point is C++26, where noexcept functions turn a throwing violation handler into std::terminate.