You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 6 Next »

Work In Progress

This practice is an incomplete work in progress. It may contain errors and should not be applied until this notice has been removed.

A proper handling of errors and exceptional situations is essential for the continued correct operation of software (see ERR00-CPP. Adopt and implement a consistent and comprehensive error-handling policy). The preferred mechanism for reporting errors in a C++ program is exceptions (see ERR07-CPP. Use exception handling rather than error codes). A number of core language facilities, including dynamic_cast, operator new(), and typeid, report failures by throwing exceptions. In addition, the C++ Standard Library makes heavy use of exceptions to report several different kinds of failures. Few C++ programs manage to avoid making use of some of these facilities. Thus, the vast majority of C++ programs must be prepared for exceptions to occur and handle each appropriately.

Since exceptions introduce code paths into a program that wouldn't exist in their absence it is important to consider the effects of code taking such paths and to avoid any undesirable effects that might arise otherwise. Some such effects include a failure to release an acquired resource and introducing a leak, a failure to re-establish a class invariant after a partial update to an object, or even a partial object update while maintaining all invariants. Code that avoids any such undesirable effects is said to be exception safe.

Based on the effects mentioned above we can distinguish among three kinds of exception safety guarantees in decreasing desirability:

Guarantee

Description

Example

Strong

The strong exception safety guarantee is a property of an operation such that, in addition to satisfying the basic exception safety guarantee, if the operation terminates by raising an exception it has no observable effects on program state. (See strong exception safety.)

#Strong Exception Safety

Basic

The basic exception safety guarantee is a property of an operation such that, if the operation terminates by raising an exception, it preserves program state invariants and prevents resource leaks. (See basic exception safety.)

#Basic Exception Safety

None

Code that provides neither the strong nor the basic exception safety guarantee is not exception safe.

#No Exception Safety

Code that provides no exception safety guarantee is unsafe and must be considered defective.

Non-Compliant Code Example (No Exception Safety)

The following noncompliant example shows a flawed implementation of the copy assignment operator of a dynamically sizable array class. The implicit invariants of the class are that the array member is a valid (possibly null) pointer and that the nelems member stores the number of elements in the array pointed to by array.

The copy assignment operator is flawed because it fails to provide any exception safety guarantee. The function deallocates array and assigns the element counter, nelems, before allocating a new block of memory for the copy. As a result, when the new expression throws an exception, the function will have modified the state of both member variables in a way that violates the implicit invariants of the class. Consequently, the object of the class is in an indeterminate state and any operation on it, including its destruction, results in undefined behavior.

class IntArray {
  int *array;
  std::size_t nelems;
public:
  // ...

  ~IntArray() {
    delete[] array;
  }

  IntArray& operator=(const IntArray &rhs) {
    if (this != &rhs) {
      delete[] array;
      nelems = rhs.nelems;
      array = new int[nelems];
      std::memcpy(array, rhs.array, nelems * sizeof *array);
    }
    return *this;
  }

  // ...
};

Compliant Solution (Strong Exception Safety)

In the compliant solution below, the copy assignment operator provides the Strong Exception Safety guarantee. The function takes care to allocate new storage for the copy before changing the state of the object. Only after the allocation succeeds does the function proceed to change the state of the object. In addition, by copying the array to the newly allocated storage before deallocating the existing array the function avoids the test for self-assignment, thus improving the performance of the code in the common case.

class IntArray {
  int *array;
  std::size_t nelems;
public:
  // ...

  ~IntArray() {
    delete[] array;
  }

  IntArray& operator=(const IntArray &rhs) {
    int* const tmp = new int[rhs.nelems];
    std::memcpy(tmp, rhs.array, nelems * sizeof *array);
    delete[] array;
    array  = tmp;
    nelems = rhs.nelems;
    return *this;
  }

  // ...
};

Risk Assessment

Code that is not exception safe typically leads to resource leaks, causes the program to be left in an inconsistent or unexpected state, and ultimately results in undefined behavior at some point after the first exception is thrown.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ERR39-CPP

high

likely

high

P27

L1

Other Languages

TO DO

Bibliography

[CWE] CWE-390: Detection of Error Condition Without Action
[CWE] CWE-460: Improper Cleanup on Thrown Exception
[CWE] CWE-703: Failure to Handle Exceptional Conditions
[CWE] CWE-754: Improper Check for Unusual or Exceptional Conditions
[CWE] CWE-755: Improper Handling of Exceptional Conditions
[ISO/IEC 14882-2003]
[MISRA 08] Rule 15-3-2, 15-3-4
[Sutter 00] Sutter, Herb. Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions
[Sutter 01] Sutter, Herb. More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions


ERR14-CPP. Do not allow an exception class's copy constructor to throw exceptions      12. Exceptions and Error Handling (ERR)      ERR31-CPP. Don't redefine errno

  • No labels