ArticleslgStudy

science

Exception safety

Exception safety is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Exception safety rather than just read about it. In short: Exception safety is the state of code working correctly when exceptions are thrown. To aid in ensuring exception safety, C++ standard library developers have devised a set of exception safety levels, contractual guarantees of the behavior of a data structure's operations with regard to exceptions.

Key takeaways

  • Exception safety belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Exception safety to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Exception safety from memory before moving on to harder problems.

Reference excerpt

Exception safety is the state of code working correctly when exceptions are thrown. To aid in ensuring exception safety, C++ standard library developers have devised a set of exception safety levels, contractual guarantees of the behavior of a data structure's operations with regard to exceptions. Library implementers and clients can use these guarantees when reasoning about exception handling 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 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 invariants are preserved. Any stored data will contain valid values which may differ from the original values. Resource leaks (including memory leaks) 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, 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 (in C#), with (in Python), or try-with-resources (in Java).

Example Consider a smart vector type, such as C++'s std::vector<T> or Java's java.util.ArrayList<T>. 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:

No-throw guarantee: Implemented by ensuring that memory allocation never fails, or by defining the insert() 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 x into v succeeds, or v remains unchanged despite the allocation failure. Basic exception safety: Implemented by ensuring that the count field is guaranteed to reflect the final size of v. For example, if an error is encountered, the insert() function might completely deallocate v and reset its count field to zero. On failure, no resources are leaked, but v's old value is not preserved. No exception safety: An insertion failure might lead to corrupted content in v, an incorrect value in the count field, or a resource leak.

References

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

Worked examples

Example 1 — a first encounter with Exception safety

Start with the simplest possible case. Write down what Exception safety claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Exception safety before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Exception safety ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Exception safety

In research
Exception safety appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Exception safety in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Exception safety is common in secondary-school and first-year university syllabi. It links to neighbouring topics C++, Control flow, Programming language topics, so understanding it makes those chapters shorter.
In everyday life
Look for Exception safety outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Exception safety” →

How to study Exception safety in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Exception safety means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Exception safety out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Exception safety in simple terms?

Exception safety is the state of code working correctly when exceptions are thrown. To aid in ensuring exception safety, C++ standard library developers have devised a set of exception safety levels, contractual guarantees of the behavior of a data structure's operations with regard to exceptions.

Why does Exception safety matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Exception safety?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Exception safety.

Tags

  • C++
  • Control flow
  • Programming language topics

Keep exploring