Handling of C++ Exceptions #301
Replies: 1 comment
-
Originally answered in #677. The ProblemA 100% MC/DC coverage must be achieved for all parts of the code. When implementing constructs that perform bounce checks, and on failure abort the execution and transition to a safe state, this must also be tested. The standard approach is to override the fatal error handler and replace it with an exception. However, this approach can only be used if all underlying constructs are at least weak exception-safe and the test code does not contain any undefined behavior. Weak Exception SafetyAn operation providing a weak guarantee ensures that, in the event of errors or exceptions, related objects remain in a consistent but unspecified state. What constitutes "consistency" can vary, but at a minimum, each object can be safely destroyed or reassigned. Strong Exception SafetyAn operation providing a strong guarantee ensures that, in the event of errors or exceptions, all related objects remain in the same state they were in at the beginning. Implementation: Copy-And-Swap IdiomTo reassign a complex object with a strong exception safety guarantee, the copy-and-swap idiom is often used in C++:
If the swap operation is never reached due to an exception, the contents of |
Beta Was this translation helpful? Give feedback.
-
In general C++ code shall be compiled with
-fexceptions
(i.e., with support for C++ exceptions). The chapter Exceptions - Doing Without of the GNU libstdc++ reference manual explains why:Anyhow in safety-related code, exceptions shall only be used for non-recoverable errors as the stack unwinding itself is not deterministic and not part of the qualification scope of most qualified compilers.
Therefore C++ exceptions shall be avoided.
Anyhow as some libraries e.g. the C++ STL cannot be refactored it can occur that a piece of code which is linked to a safety application throws an exception.
If safety-related code throws an exception, the program shall terminate immediately.
This is necessary to prevent the nondeterministic behavior of exception handling (e.g., unbounded worst-case execution time of destructors during stack unwinding, memory exhaustion during the allocation for the exception to be thrown).
Example implementation:
According to the Itanium C++ ABI Specification, throwing an exception looks like this:
To abort as early as possible
__cxa_allocate_exception()
can be overloaded as it is the first function that is called when throwing an exception.Overload
__cxa_allocate_exception()
to immediately callstd::abort()
:Beta Was this translation helpful? Give feedback.
All reactions