Lesson 2 of 5
Exception Safety & noexcept
**Exception safety** describes what happens to your program state when an exception is thrown. The four levels: **nothrow** (never throws), **strong** (rollback on exception - transactional), **basic** (no leak/corruption but state may change), and **none** (may corrupt state - never acceptable). `noexcept` declares that a function doesn't throw - the compiler can optimise accordingly, and STL containers use it to choose between move (if noexcept) and copy (if not) during reallocation.
Exception Safety Levels, noexcept & the Strong Guarantee
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <algorithm>
#include <type_traits>
// ── nothrow guarantee ─────────────────────────────────────────
void swap_nothrow(int& a, int& b) noexcept {
int tmp = a; a = b; b = tmp; // cannot throw - nothrow guarantee
}
// ── Strong guarantee - rollback on failure ────────────────────
class Database {
std::vector<std::string> records_;
public:
// Strong guarantee: if anything throws, records_ is unchanged
void add_record(std::string record) {
std::vector<std::string> backup = records_; // make a copy
try {
if (record.empty()) throw std::invalid_argument("Empty record");
records_.push_back(std::move(record)); // actual mutation
// ... if this throws (e.g., allocation), backup is still valid
} catch (...) {
records_ = std::move(backup); // restore (swap idiom better)
throw; // rethrow - caller knows it failed
}
// backup goes out of scope (destructor runs regardless)
}
// Better strong guarantee via copy-and-swap
void add_record_cns(std::string record) {
std::vector<std::string> copy = records_; // copy first
copy.push_back(std::move(record)); // modify copy
// If we reach this line, copy is in the desired state
std::swap(records_, copy); // noexcept swap - cannot fail!
// old data destroyed in copy's destructor
}
size_t size() const noexcept { return records_.size(); }
const std::vector<std::string>& records() const noexcept { return records_; }
};
// ── noexcept specification ─────────────────────────────────────
int parse_int(const std::string& s) noexcept {
try {
return std::stoi(s);
} catch (...) {
return -1; // absorb exception - returns sentinel
}
}
struct Point {
double x, y;
// Move constructor: noexcept → STL will move, not copy, during reallocation
Point(double x, double y) noexcept : x(x), y(y) {}
Point(Point&&) noexcept = default; // explicitly mark noexcept
Point& operator=(Point&&) noexcept = default;
};
void noexcept_demo() {
// noexcept() operator - compile-time query
std::cout << "swap_nothrow noexcept? "
<< noexcept(swap_nothrow(*(int*)nullptr, *(int*)nullptr)) << "
"; // 1
std::cout << "parse_int noexcept? "
<< noexcept(parse_int("")) << "
"; // 1
// vector uses noexcept to decide move vs copy
std::vector<Point> vp;
vp.reserve(5);
// Point's move is noexcept → vector moves on reallocation (O(1))
for (int i = 0; i < 10; ++i) {
vp.emplace_back((double)i, (double)i); // realloc: moves Points
}
std::cout << "Points in vector: " << vp.size() << "
";
// static_assert noexcept - document expectations
static_assert(std::is_nothrow_move_constructible_v<Point>);
}
int main() {
Database db;
db.add_record_cns("First");
db.add_record_cns("Second");
try {
db.add_record_cns(""); // throws invalid_argument
} catch (const std::invalid_argument& e) {
std::cerr << "Caught: " << e.what() << "
";
}
std::cout << "DB size after failed add: " << db.size() << "
"; // still 2
noexcept_demo();
return 0;
}Common Mistakes
- Marking `noexcept` when the function can actually throw - if a `noexcept` function throws, `std::terminate()` is called immediately (no catch possible). Never mark a function `noexcept` unless you're certain it won't throw or you internally catch all exceptions.
- Conditional `noexcept` - for wrapper functions that merely forward, use `noexcept(noexcept(expression))`: `void swap(T& a, T& b) noexcept(noexcept(a.swap(b)));` - the function is noexcept if and only if `a.swap(b)` is noexcept. This propagates exception specifications correctly.
- Not using the strong guarantee pattern for transactional operations - operations that update multiple data structures must either succeed completely or fail cleanly. The copy-and-swap pattern provides this: modify a copy, commit with a noexcept swap.
Tip
Tip
Practice Exception Safety noexcept in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Basic, Strong, and Nothrow safety guarantees across critical code paths
Practice Task
Note
Practice Task - (1) Write a working example of Exception Safety noexcept from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Exception Safety noexcept is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- **Exception safety** describes what happens to your program state when an exception is thrown.
- Marking `noexcept` when the function can actually throw - if a `noexcept` function throws, `std::terminate()` is called immediately (no catch possible). Never mark a function `noexcept` unless you're certain it won't throw or you internally catch all exceptions.
- Conditional `noexcept` - for wrapper functions that merely forward, use `noexcept(noexcept(expression))`: `void swap(T& a, T& b) noexcept(noexcept(a.swap(b)));` - the function is noexcept if and only if `a.swap(b)` is noexcept. This propagates exception specifications correctly.
- Not using the strong guarantee pattern for transactional operations - operations that update multiple data structures must either succeed completely or fail cleanly. The copy-and-swap pattern provides this: modify a copy, commit with a noexcept swap.
Finished this lesson?