Learn C++
#include "exceptionhandling/exception_safety.hpp"

Exception Safety Guarantees in C++

//concept

Exception safety grades how code behaves when throws interrupt it: no-throw (never fails — swaps, moves, destructors), strong (commit-or-rollback — failed operations leave state untouched), basic (no leaks, invariants hold, but state may change), and none (all bets off). RAII delivers basic safety almost free; strong safety takes deliberate patterns like copy-and-swap.

Design rule: mutating operations should offer at least basic, widely-used ones strong, and destructors plus swaps no-throw unconditionally. Document the grade per function — callers writing transactional code need to know what failures leave behind.

//how it works
1

No-throw: can't fail

Swaps, moves, destructors, and deallocations must never throw — mark them noexcept to promise it.

2

Strong: all or nothing

Copy-and-swap: build the new state aside, then commit with a non-throwing swap — observers see old or new, never half.

3

Basic: no leaks, valid state

RAII members guarantee this baseline — resources freed, invariants intact, even if values changed mid-operation.

4

Destructors never throw

A throwing destructor during unwinding calls std::terminate — catch everything inside destructors, always.

//example
#include <iostream>
#include <vector>
#include <string>
 
int main() {
std::vector<std::string> v{"a"};
try {
v.reserve(1000000000ULL * 1000ULL);
} catch (const std::bad_alloc&) {
std::cout << "kept " << v.size() << std::endl;
}
return 0;
}
Output
kept 1
1The absurd reserve request fails with bad_alloc instead of corrupting anything.
2vector's strong guarantee holds: the failed reallocation left the original element untouched.
3kept 1 prints — the operation rolled back to exactly the pre-call state.
//use cases
transactional updates via copy-and-swap in editors and databases
Auditing destructors and swaps for unconditional no-throw
Relying on STL strong guarantees (push_back either succeeds or preserves)
Documenting each API's guarantee level for transactional callers

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.