Exception-safe
   HOME

TheInfoList



OR:

Exception safety is the state of code working correctly when exceptions are thrown. To aid in ensuring exception safety,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
standard library developers have devised a set of ''exception safety levels'', contractual guarantees of the behavior of a data structure's operations with regards to exceptions. Library implementers and clients can use these guarantees when reasoning about
exception handling In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' โ€“ anomalous or exceptional conditions requiring special processing โ€“ during the execution of a program. In general, an ...
correctness. The exception safety levels apply equally to other languages and error-handling mechanisms.


History

As David Abrahams writes, "nobody ever spoke of 'error-safety' before C++ had exceptions." The term appeared as the topic of publications in JTC1/SC22/WG21, the C++ standard committee, as early as 1994. Exception safety for the C++ standard library was first formalized for STLport by Abrahams, establishing the basic safety/strong safety distinction. This was extended to the modern basic/strong/nothrow guarantees in a later proposal.


Background

Exceptions provide a form of non-local control flow, in that an exception may "bubble up" from a called function. This bubbling can cause an exception safety bug by breaking invariants of a mutable data structure, as follows: # A step of an operation on a mutable data structure modifies the data and breaks an invariant. # An exception is thrown and control "bubbles up", skipping the rest of the operation's code that would restore the invariant # The exception is caught and recovered from, or a finally block is entered # The data structure with broken invariant is used by code that assumes the invariant, resulting in a bug Code with a bug such as the above can be said to be "exception unsafe".


Classification

The
C++ standard library The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard.ISO/IEC (2018). '' ISO/IEC 9899:2018(E): Programming Languages - C ยง7'' Starting from the original ANSI C standard, it wa ...
provides several levels of exception safety (in decreasing order of safety): # 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. # 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. # Basic exception safety: Partial execution of failed operations can result in side effects, but all
invariant Invariant and invariance may refer to: Computer science * Invariant (computer science), an expression whose value doesn't change during program execution ** Loop invariant, a property of a program loop that is true before (and after) each iteratio ...
s are preserved. Any stored data will contain valid values which may differ from the original values.
Resource leak In computer science, a resource leak is a particular type of resource consumption by a computer program where the program does not release resources it has acquired. This condition is normally the result of a bug in a program. Typical resource lea ...
s (including
memory leak In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that Computer memory, memory which is no longer needed is not released. A memory leak may also happe ...
s) are commonly ruled out by an invariant stating that all resources are accounted for and managed. # 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. A key mechanism for exception safety is a finally clause, or similar
exception handling syntax Exception handling syntax is the set of keywords and/or structures provided by a computer programming language to allow exception handling, which separates the handling of errors that arise during a program's operation from its ordinary processes. ...
, 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 In object-oriented programming, the dispose pattern is a design pattern for resource management. In this pattern, a resource is held by an object, and released by calling a conventional method โ€“ usually called close, dispose, free, release dep ...
, 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 (for example, by having the function return a boolean result indicating whether the insertion took place). ;Strong exception safety: Implemented by doing any necessary allocation first, and then swapping buffers if no errors are encountered (the copy-and-swap idiom). 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 In computer science, a resource leak is a particular type of resource consumption by a computer program where the program does not release resources it has acquired. This condition is normally the result of a bug in a program. Typical resource lea ...
.


References

{{cite book , author=Bjarne Stroustrup , author-link=Bjarne Stroustrup , title=Appendix E: Standard-Library Exception Safety in "The C++ Programming Language" , year=1997 , edition=3rd , publisher=Addison-Wesley , isbn=0-201-88954-4, url=https://www.stroustrup.com/3rd_safe.pdf


External links

* Herb Sutter: Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions, 2000 * Jon Kalb
Exception-Safe Coding in C++
with C++Now! 2012 presentations on exception safety. * Related discussion on Stackoverflow
C++: do you (really) write exception safe code
C++ Control flow Programming language topics