Rule A15-4-2 (required, implementation, automated)
If a function is declared to be noexcept, noexcept(true) or noexcept(
), then it shall not exit with an exception.
Rationale
If a function declared to be noexcept, noexcept(true) or noexcept(true condition) throws an exception, then std::terminate() is called immediately. It is implementationdefined whether the call stack is unwound before std::terminate() is called. To ensure that the rule is not violated, if function’s noexcept specification can not be determined, then always declare it to be noexcept(false).
Example
//% $Id: A15-4-2.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
2 #include <stdexcept>
// library.h
void LibraryFunc();
// project.cpp
void F1() noexcept
{
// ...
Non-compliant - f1 declared to be
throw std::runtime_error("Error");
noexcept, but exits with exception.
This leads to std::terminate() call
}
void F2() noexcept(true)
{
try
{
// ...
throw std::runtime_error(
"Error");
// Compliant - exception will not leave f2
}
catch (std::runtime_error& e)
{
// Handle runtime error
}
}
void F3() noexcept(false)
{
// ...
throw std::runtime_error("Error"); // Compliant
}
void F4() noexcept(
false) // Compliant - no information whether library_func() throws or not
{
LibraryFunc();
}
See also
MISRA C++ 2008 [7]: 15-5-2: Where a function’s declaration includes an exception-specification, the function shall only be capable of throwing exceptions of the indicated type(s). MISRA C++ 2008 [7]: 15-5-3: The terminate() function shall not be called implicitly. HIC++ v4.0 [9]: 15.3.2: Ensure that a program does not result in a call to std::terminate SEI CERT C++ Coding Standard [10]: ERR50-CPP: Do not abruptly terminate the program.