AUTOSAR C++14 Rule M15-1-1
The assignment-expression of a throw statement shall not itself cause an exception to be thrown
Since R2020b
Description
Rule Definition
The assignment-expression of a throw statement shall not itself cause an exception to be thrown.
Rationale
In C++, you can use a throw
statement to raise exceptions explicitly.
The compiler executes such a throw
statement in two steps:
First, it creates the argument for the
throw
statement. The compiler might call a constructor or evaluate an assignment expression to create the argument object.Then, it raises the created object as an exception. The compiler tries to match the exception object to a compatible handler.
If an unexpected exception is raised when the compiler is creating the
expected exception in a throw
statement, the unexpected exception is
raised instead of the expected one. Consider this code where a throw
statement raises an explicit exception of class
myException
.
class myException{ myException(){ msg = new char[10]; //... } //... }; foo(){ try{ //.. throw myException(); } catch(myException& e){ //... } }
myException
object, the
new
operator can raise a bad_alloc
exception. In
such a case, the throw
statement raises a bad_alloc
exception instead of myException
. Because myException
was the expected exception, the catch block is incompatible with
bad_alloc
. The bad_alloc
exception becomes an
unhandled exception. It might cause the program to abort abnormally without unwinding the
stack, leading to resource leak and security vulnerabilities.Unexpected exceptions arising from the argument of a throw
statement
can cause resource leaks and security vulnerabilities. To prevent such unwanted outcome,
avoid using expressions that might raise exceptions as argument in a
throw
statement.
Polyspace Implementation
Polyspace® flags the expressions in throw
statements that can raise an
exception. Expressions that can raise exceptions can include:
Functions that are specified as
noexcept(false)
Functions that contain one or more explicit
throw
statementsConstructors that perform memory allocation operations
Expressions that involve dynamic casting
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Exception handling |
Category: Required, Automated |
Version History
Introduced in R2020b