# C++ Exception safety **[Exception safety](https://en.cppreference.com/w/cpp/language/exceptions)** 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. ```cpp // compile: g++ -o except except.cpp // run: ./except // description: exception safety levels and RAII guarantees #include #include #include class TransactionalUpdate { private: std::vector data; public: void update(const std::vector& new_data) { // Exception before swap: data unchanged (strong safety) std::vector 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; } ```