Table of Contents

C++ Exception safety

Exception safety describes guarantees a function makes about state if an exception is thrown. The three levels are: basic safety (invariants held, no leaks), strong safety (transaction-like: either succeeds or state unchanged), and nothrow safety (never throws). RAII and smart pointers help achieve these guarantees automatically.

Design functions for strong or nothrow safety when possible; document the guarantee your code provides.

Example

This example shows strong exception safety using RAII and copy-and-swap.

// compile: g++ -o except except.cpp
// run: ./except
// description: exception safety levels and RAII guarantees
 
#include <iostream>
#include <vector>
#include <memory>
 
class TransactionalUpdate {
private:
    std::vector<int> data;
public:
    void update(const std::vector<int>& new_data) {
        // Exception before swap: data unchanged (strong safety)
        std::vector<int> temp = new_data;  // may throw
        data = std::move(temp);            // noexcept swap
    }
 
    void print() const {
        for (int x : data) std::cout << x << " ";
        std::cout << "\n";
    }
};
 
int main() {
    TransactionalUpdate t;
    t.update({1, 2, 3});
    t.print();
 
    return 0;
}