Why is this an issue?
When an exception is a pointer, it is difficult for the code that catches the exception to determine whether or not it needs to delete the
pointed-to object. It is even more complicated than a traditional manual memory management scenario because the throw
and the
corresponding catch
can be far apart.
How to fix it
Throwing by value is more straightforward and less error-prone than using a pointer as an exception object.
Code examples
Noncompliant code example
std::out_of_range globalException("Index too high");
void fn(int i) {
// In this situation, the developer writing the "catch" has no way of knowing if the object pointed to by
// the exception should be deleted or not
if (i > 10) {
throw (&globalException); // Noncompliant: the catch is supposed not to delete the pointer
} else {
throw (new std::out_of_range{"Invalid index"}); // Noncompliant: the catch is supposed to delete the pointer
}
}
Compliant solution
std::out_of_range globalException("Index too high");
void fn(int i) {
if (i > 10) {
throw (globalException); // Compliant: it throws a copy of the global variable
} else {
throw (std::out_of_range{"Invalid index"}); // Compliant: it throws a new object
}
}
Resources
External coding guidelines
- MISRA C++ 2008, 15-0-2 - An exception object should not have pointer type.
Related rules
- S1044 - Exception classes should be caught by reference