MISRA C++:2008 Rule 15-1-1
The assignment-expression of a throw statement shall not itself cause an exception to be thrown
Description
Rule Definition
The assignment-expression of a throw statement shall not itself cause an exception to be thrown.1
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
throwstatement. 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
throwstatementsConstructors 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 |
Version History
Introduced in R2020b
1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.