Exception Safety

Use exception-safe practices like smart pointers in C++ (std::unique_ptr, std::shared_ptr), which manage memory automatically even when exceptions occur.

4 Levels of Exception Safety

  1. No exception safety - If an exception is thrown - no guarantees about program state - object has invalid memory, memory is leaked, program crashes.
  2. Basic guarantee - if an exception is thrown - program is in a valid, but unspecified state. Ex: Class invariants are maintained, no memory is leaked.
  3. Strong guarantee - If an exception is thrown, the program reverts back to its state before the method was called. Ex: vector::emplace_back
    • Either it succeeds, or if exception is thrown, vector is in its prior state
  4. Nothrow guarantee - exceptions are never propagated outside of the function call - always does its job. Ex: vector::size gives nothrow guarantee, always returns size of vector without fail.