Thrown exceptions that are not explicitly caught subject a running program to implementation-defined behavior culminating in abnormal termination. According to section 15.3 "Handling an Exception" of C++2003 [ISO/IEC 14882-2003]:
If no matching handler is found in a program, the function
std::terminate()is called; whether or not the stack is unwound before this call to
std::terminate()is implementation-defined (15.5.1).
The effects of
std::terminate() are to call the
terminate_handler function in effect immediately after evaluating the throw-expression. The default
std::abort(), which has the effect of causing abnormal process termination to occur. Abnormal process termination is the typical vector for denial of service attacks.
Consequently, programs should take steps to prevent
std::terminate() from being invoked for at least two reasons:
- If the stack is not unwound then destructors of local objects are not invoked, acquired system-wide or application-wide resources may not be released, file buffers are not flushed, database transactions are not committed or rolled back, etc.
- Since failing to catch an exception involves implementation-defined behavior, to comply MSC14-CPP. Do not introduce unnecessary platform dependencies.
Rather, programs should catch all exceptions and attempt to recover at the earliest opportunity. Under the rare circumstances when recovery is not feasible (for example, when a logic error is detected), programs should gracefully terminate after indicating the nature of the problem to the operator. See also ERR04-CPP. Choose an appropriate termination strategy.
Non-Compliant Code Example (
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.
Compliant Solution (
In this code example, all exceptions are caught, allowing normal termination, even in the face of unexpected errors (albeit with an exit status indicating that an error occurred).
Compliant Solution (
An alternative is to wrap all of
main()'s functionality inside a try-catch block and catch and handle exceptions by exiting with a status indicating an error to the invoking process.
Failing to handle exceptions can lead to resources not being freed, closed, etc.
This rule appears in the Java Secure Coding Standard as EXC08-J. Try to gracefully recover from system errors.