Legacy C++ › 5. Exceptions, Strings and I/O
Exception Safety
Basic, strong and no-throw guarantees and how to achieve them.
advanced #exception-safety#raii#strong-guarantee#no-throw
Explanation
Code is exception safe if throwing at any point leaves the program in a well-defined state. The standard guarantees (due to David Abrahams) are:
| Guarantee | Promise |
|---|---|
| No-throw | the operation never throws (swap, destructors, simple pointer assignment) |
| Strong | commit-or-rollback: if it throws, the state is exactly as before |
| Basic | if it throws, nothing leaks and invariants hold, but values may have changed |
| None | leaks or corrupt state: unacceptable |
Techniques:
- RAII: every resource is owned by an object whose destructor releases it.
- Do the throwing work first on temporaries, then commit with no-throw operations (the swap trick).
- Keep destructors,
swapand move operations non-throwing.
Example
#include <iostream>
#include <stdexcept>
struct Resource {
int id;
explicit Resource(int i) : id(i) {
if (i == 3) throw std::runtime_error("cannot create resource 3");
}
};
// UNSAFE: if the second 'new' throws, 'a' leaks.
void unsafe() {
Resource* a = new Resource(1);
Resource* b = new Resource(3); // throws -> a is never deleted
delete b; delete a;
}
// A tiny RAII owner
template <typename T>
class Holder {
T* p_;
Holder(const Holder&); // non-copyable (C++03 style)
Holder& operator=(const Holder&);
public:
explicit Holder(T* p) : p_(p) {}
~Holder() { delete p_; }
T* get() const { return p_; }
};
// SAFE: each resource is owned immediately.
void safe() {
Holder<Resource> a(new Resource(1));
Holder<Resource> b(new Resource(3)); // throws -> a's destructor runs
}
int main() {
try { safe(); }
catch (const std::exception& e) { std::cout << "caught: " << e.what() << "\n"; }
return 0;
}
Common pitfalls
f(Holder<T>(new A), Holder<T>(new B)): argument evaluation order is unspecified, sonew Bmay throw afternew Aand before its owner exists. Create named owners first.- Assignment operators that destroy the old state before the new state is ready can’t offer the strong guarantee (use copy-and-swap).
- Destructors that can throw make all of the above impossible.
- Catching an exception and ignoring it is not exception safety.
std::vector::push_backoffers the strong guarantee only if element copying/moving doesn’t throw (or if the type is copyable).
Legacy vs modern
C++11’s std::unique_ptr/make_unique, noexcept, and move semantics (std::move_if_noexcept) make safe code far easier to write.
Exercises
1. Which guarantee does std::swap on two ints provide?
No-throw: it only copies built-in values.