Exception Safety & noexcept
The three guarantees (plus "none")
| Level | Promise if an exception is thrown |
|---|---|
| No-throw | it never throws (noexcept) |
| Strong | state is unchanged, as if the call never happened (commit or rollback) |
| Basic | no leaks, all objects still valid, but state may have changed |
| None | anything goes — avoid |
Every function should give at least the basic guarantee; RAII makes that natural.
Achieving the strong guarantee: do the work on the side, then commit
void set_items(std::vector<Item> items) {
validate(items); // may throw: nothing changed yet
auto copy = build(items); // may throw: nothing changed yet
items_.swap(copy); // noexcept commit ✅
}
The copy-and-swap idiom (lesson 10.4) applies the same idea.
noexcept
void swap(Buffer& other) noexcept;
Buffer(Buffer&&) noexcept;
- Promise that the function doesn't throw
- If it throws anyway →
std::terminate(no unwinding to callers) - Enables optimizations:
std::vectoronly moves elements during reallocation if the move constructor isnoexcept(otherwise it copies to keep the strong guarantee) noexcept(expr)operator checks at compile time whether an expression is noexcept
What should be noexcept ✅
- Destructors (implicitly noexcept)
- Move constructors and move assignment
swapfunctions- Simple getters, functions that can't fail
Destructors must not throw
If a destructor throws during stack unwinding, the program terminates. Catch and log inside instead.
Practical rules
- Acquire resources with RAII objects only
- Change state only after everything that can throw has succeeded
- Don't leave objects half-updated
- Mark moves and swaps
noexcept
Example
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
class Ledger {
public:
// Strong guarantee: validate and build a new vector first, then commit with a no-throw swap
void replace_all(const std::vector<double>& amounts) {
std::vector<double> fresh;
fresh.reserve(amounts.size());
for (double a : amounts) {
if (a == 0) throw std::invalid_argument("zero amount in import");
fresh.push_back(a); // may throw: ledger untouched so far
}
entries_.swap(fresh); // commit: noexcept
}
// Basic guarantee only: if it throws midway, some entries were already added
void append_unsafely(const std::vector<double>& amounts) {
for (double a : amounts) {
if (a == 0) throw std::invalid_argument("zero amount in append");
entries_.push_back(a);
}
}
std::size_t size() const noexcept { return entries_.size(); }
private:
std::vector<double> entries_ = { 100, 200 };
};
struct Tracked {
std::string name;
explicit Tracked(std::string n) : name(std::move(n)) {}
Tracked(const Tracked& o) : name(o.name) { ++copies; }
Tracked(Tracked&& o) noexcept : name(std::move(o.name)) { ++moves; } // noexcept lets vector move
static inline int copies = 0, moves = 0;
};
struct MaybeThrowingMove {
std::string name;
explicit MaybeThrowingMove(std::string n) : name(std::move(n)) {}
MaybeThrowingMove(const MaybeThrowingMove& o) : name(o.name) { ++copies; }
MaybeThrowingMove(MaybeThrowingMove&& o) : name(std::move(o.name)) { ++moves; } // NOT noexcept
static inline int copies = 0, moves = 0;
};
int main() {
Ledger l;
try { l.replace_all({ 5, 0, 7 }); } catch (const std::exception& e) { std::cout << "replace_all failed: " << e.what() << '\n'; }
std::cout << "entries after failed replace_all: " << l.size() << " (unchanged: strong guarantee)\n";
try { l.append_unsafely({ 5, 0, 7 }); } catch (const std::exception& e) { std::cout << "append failed: " << e.what() << '\n'; }
std::cout << "entries after failed append: " << l.size() << " (partly changed: basic guarantee)\n";
std::vector<Tracked> a;
std::vector<MaybeThrowingMove> b;
for (int i = 0; i < 17; ++i) { a.emplace_back("x"); b.emplace_back("x"); } // several reallocations
std::cout << "noexcept move: copies " << Tracked::copies << ", moves " << Tracked::moves << '\n';
std::cout << "throwing move: copies " << MaybeThrowingMove::copies << ", moves " << MaybeThrowingMove::moves << '\n';
std::cout << std::boolalpha << "size() is noexcept? " << noexcept(l.size())
<< ", replace_all is noexcept? " << noexcept(l.replace_all({})) << '\n';
return 0;
}
/* Output:
replace_all failed: zero amount in import
entries after failed replace_all: 2 (unchanged: strong guarantee)
append failed: zero amount in append
entries after failed append: 3 (partly changed: basic guarantee)
noexcept move: copies 0, moves 31
throwing move: copies 31, moves 0
size() is noexcept? true, replace_all is noexcept? false
*/