This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 18.3.1 - There should be at least one exception handler to catch all otherwise unhandled exceptions
[except.terminate] Implementation 1.2, 1.10
Category: Advisory
Analysis: Decidable,Single Translation Unit
Amplification
The function main should include a try-catch with a catch ( ... ) handler.
The catch handlers of this try-block, and any code within main that is outside of this try-block, should
not attempt to propagate an exception. To make this rule decidable, any call to a function having a potentially-throwing exception
specification ([except.spec]/3) is assumed to propagate an exception.
For the purposes of this rule, where a development environment allows a function other than main to be nominated as the entry point of
the program, that function shall be treated as if it were main.
Rationale
If a program throws an exception that is not caught, the program terminates in an implementation-defined manner. In particular, it is
implementation-defined whether the call stack is unwound before termination, meaning that some destructors may not be executed. By enforcing
the provision of a "last-ditch catch-all", the developer can ensure that the program terminates in a consistent manner.
Example
int main() // Compliant
{
try
{
// Program code
}
catch ( specific_type & e ) // Optional, explicit handler(s) are permitted
{
// Handle expected exceptions
}
catch ( ... ) // Catch-all handler should be provided
{
// Handle unexpected exceptions
}
return 0;
}
void logError( char const * message );
int main() // Compliant
try
{
// Program code
}
catch ( ... ) // Catch-all handler
{
try
{
logError( "Unexpected" );
}
catch (...)
{
// Logging also threw
}
}
int main() // Non-compliant - handler may throw
try
{
// Program code
}
catch ( ... ) // Catch-all handler
{
logError( "Unexpected"); // Potentially throwing function may lead to
} // an exception propagating from main
Copyright The MISRA Consortium Limited © 2023