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

Compare with Current View Page History

Version 1 Next »

Thrown exceptions that are not explicitly caught subject the program to several implementation-dependent issues. C++2004, section 15.5.1 "The std::terminate() function", says:

...when the exception handling mechanism cannot find a handler for a thrown exception (15.3).

In such cases, std::terminate() is called (18.7.3). In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before std::terminate() is called. In all other situations, the stack shall not be unwound before std::terminate() is called. An implementation is not permitted to finish stack unwinding prematurely based on a determination that the unwind process will eventually cause a call to std::terminate().

Consequently you should take steps to prevent std::terminate() from being invoked for two reasons. First because it involves implementation-defined behavior. Second, if the stack is not unwound on your platform, than RAII is violated. That is, destructors are not called, allocated memory is not freed, opened files are not flushed and closed, etc.

Non-Compliant Code Example (main())

In this example, main() does several useful work but does not catch any exceptions. Consequently, any exceptions thrown will call std::terminate(), and might not destroy any objects owned by the program.

int main(int argc, char** argv) {
  Object object; // might not get destroyed if exception thrown
  // do useful work
  return 0;
}

Compliant Solution (main())

In this code example, all exceptions are caught, allowing normal termination, even in the face of unexpected errors.

int main(int argc, char** argv) {
  Object object;
  bool error = false;

  try {
    // do useful work
  } catch (...) {
    error = true;
  }

  return error ? -1 : 0; // object gets destroyed here
}

Risk Assessment

Failing to handle exceptions can lead to resources not being freed, closed, etc.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ERR12-C

1 (low)

1 (unlikely)

1 (low)

P1

L3

References

[[ISO/IEC 14882-2003]]
[[MISRA 08]] Rule 15-3-2


ERR09-CPP. Throw anonymous temporaries and catch by reference      12. Exceptions and Error Handling (ERR)      ERR31-CPP. Don't redefine errno

  • No labels