C++
Exception safety
Learn exception safety guarantees.
Exception safety guarantees
The exception safety guarantee of a function describes how it preserves program state when an exception is thrown. There are three main guarantees: basic, strong and nothrow.
Basic guarantee: after an exception the object stays in a valid state, no resource leaks. Strong guarantee: the operation either completes or the object stays exactly as it was (rollback). Nothrow guarantee: the function never throws; destructors and swap are like this. These three form the skeleton of robust code design.
Strong guarantee: copy-and-swap
The classic way to provide the strong guarantee is the copy-and-swap technique: first take a copy of the object, make the change on the copy, then swap with swap.
Example: void add_item(vector<string>& v, const string& item) { vector<string> copy = v; copy.push_back(item); v.swap(copy); }. push_back may throw when memory is full; in that case v is untouched. swap is nothrow, so the last step cannot fail. This way either the addition completes or v stays exactly as it was.
Exercise Write add_item with the strong guarantee
Write the add_item function with copy-and-swap: std::vector<std::string> copy = v;, copy.push_back(item);, v.swap(copy);. In main create std::vector<std::string> v{"a", "b"};, call add_item(v, "c") and print v.size().
Show example solution
#include <iostream>
#include <vector>
#include <string>
void add_item(std::vector<std::string>& v, const std::string& item) {
std::vector<std::string> copy = v;
copy.push_back(item);
v.swap(copy);
}
int main() {
std::vector<std::string> v{"a", "b"};
add_item(v, "c");
std::cout << v.size();
return 0;
}
Test yourself
-
Match each guarantee to its description
- basic
- Valid state
- strong
- Rollback
- nothrow
- Never throws
- swap
- Nothrow swap
-
nothrow swap
v.____(copy);
Show answer
v.swap(copy);
-
In which scenario is the strong guarantee provided?
- When the function never throws
- When the object stays as it was on exception (rollback)
- When the object is always corrupted
- When the exception is swallowed
Show answer
When the object stays as it was on exception (rollback) — Strong guarantee: the operation either completes or the object stays as it was via rollback.
Next lesson: RAII and exceptions