Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In this noncompliant example, the constructor of global may throw an exception during program startup (the std::string constructor accepting a const char * and a default allocator object is not marked noexcept(true) and consequently allows all exceptions). This exception is not caught by the function-try-block on main(), resulting in a call to std::terminate() and abnormal program termination.

Code Block
bgColor#FFcccc
langcpp
#include <string>
  
static const std::string global("...");

int main()
try {
  // ...
} catch(...) {
  // IMPORTANT: Will not catch exceptions thrown
  // from the constructor of global
}

Compliant Solution

Compliant code must prevent exceptions from escaping during program startup and termination. This compliant solution avoids defining a std::string at global namespace scope and instead uses a static const char *:

Code Block
bgColor#ccccff
langcpp
static const char *global = "...";

int main() {
  // ...
}

Risk Assessment

Throwing an exception that cannot be caught results in abnormal program termination and can lead to denial-of-service attacks.

...

Bibliography

[ISO/IEC 14882-2014]15.4, "Exception Specifications"
[Sutter 00]Item 8: ", Writing Exception-Safe Code—Part 1"

 ERR57-CPP. Do not leak resources when handling exceptions Image Removed Rule 09. Object Oriented Programming (OOP)

...

Image Added Image Added Image Added