Exception safety

Exception safety guarantees, originally formalized by David Abrahams,[1][2] are a set of contractual guidelines that class library implementers and clients can use when reasoning about exception handling safety in any programming language that uses exceptions, particularly C++.

There are several levels of exception safety (in decreasing order of safety):[3]

  1. No-throw guarantee, also known as failure transparency: Operations are guaranteed to succeed and satisfy all requirements even in exceptional situations. If an exception occurs, it will be handled internally and not observed by clients.
  2. Strong exception safety, also known as commit or rollback semantics: Operations can fail, but failed operations are guaranteed to have no side effects, so all data retain their original values.[4]
  3. Basic exception safety, also known as a no-leak guarantee: Partial execution of failed operations can cause side effects, but all invariants are preserved and no resources are leaked. Any stored data will contain valid values, even if they differ from what they were before the exception.
  4. No exception safety: No guarantees are made.

Usually, at least basic exception safety is required to write robust code. Higher levels of safety can sometimes be difficult to achieve, and might incur an overhead due to extra copying.

Example

Consider a smart vector type, such as C++'s std::vector or Java's ArrayList. When an item x is added to a vector v, the vector must actually add x to the internal list of objects and update a count field that says how many objects are in v. It may also need to allocate new memory if the existing capacity isn't sufficient.

Exception safety alternatives:

References

External references