Exception safety


Exception safety guarantees, originally formalized by David Abrahams, are a set of contractual guidelines that 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 :
  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, leaving the original values intact.
  3. Basic exception safety, also known as a no-leak guarantee: Partial execution of failed operations can result in side effects, but all invariants are preserved and there are no resource leaks. Any stored data will contain valid values which may differ from the original values.
  4. No exception safety: No guarantees are made.
Usually, at least basic exception safety is required to write robust code in such languages. Higher levels of safety can sometimes be difficult to achieve, and might incur an overhead due to extra copying. A key mechanism for exception safety is a finally clause, or similar exception handling syntax, which ensure that certain code is always run when a block is exited, including by exceptions. Several languages have constructs that simplify this, notably using the dispose pattern, named as using, with, or try-with-resources.

Example

Consider a smart vector type, such as C++'s or Java's. When an item is added to a vector, the vector must actually add to the internal list of objects and update a count field that says how many objects are in. It may also need to allocate new memory if the existing capacity isn't sufficient.
Exception safety alternatives:
;No-throw guarantee: Implemented by ensuring that memory allocation never fails, or by defining the function's behavior on allocation failure.
;Strong exception safety: Implemented by doing any necessary allocation first, and then swapping buffers if no errors are encountered. In this case, either the insertion of into succeeds, or remains unchanged despite the allocation failure.
;Basic exception safety: Implemented by ensuring that the count field is guaranteed to reflect the final size of. For example, if an error is encountered, the function might completely deallocate and reset its count field to zero. On failure, no resources are leaked, but 's old value is not preserved.
;No exception safety: An insertion failure might lead to corrupted content in, an incorrect value in the count field, or a resource leak.