The argument expression in a throw statement raises unexpected
exceptions, leading to resource leaks and security vulnerabilities
This defect occurs when the argument expression of a throw statement might raise an exception. Expressions that can raise exceptions include:
Functions that are specified as noexcept(false)
Functions that contain one or more explicit throw
statements
Constructors that perform memory allocation operations
Expressions that involve dynamic casting
When raising an exception explicitly by using throw statements, the
compiler first creates the expected exception by evaluating the argument of the throw
statement, and then raises the expected exception. If an unexpected exception is raised when
the compiler is creating the expected exception in a throw statement, the
unexpected exception is propagated instead of the expected one. This unexpected exception
might become an unhandled exception. Depending on your environment, the compiler might call
std::abort to abnormally terminate the program execution without
unwinding the stack when exceptions become unhandled, leading to resource leak and security
vulnerabilities. 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.Avoid using expressions that might raise exceptions as argument in a
throw statement.
| Group: C++ Exception |
| Language: C++ |
| Default: On for handwritten code, off for generated code |
Command-Line Syntax:
THROW_ARGUMENT_EXPRESSION_THROWS
|
| Impact: High |