Why is this an issue?
Catching an exception class by value rather than by reference can cause several problems:
- Memory is allocated unnecessarily: catching by value creates a copy of the exception object, which is destroyed at the exit of the catch block.
- Slicing occurs: the copy will be an instance of the exception base class rather than the potentially more specific exception class initially
caught. So it may lead to a loss of precision as any additional data or functionality offered by the subclass will not be accessible.
- Copying the exception class may throw an exception, leading to unexpected behavior.
How to fix it
This rule raises an issue when an exception is caught by value instead of by reference.
It is also best to avoid catching an exception by pointer (implying throwing by pointer) because it means the catch clause must manage the memory
held by the pointer. The rule S1035 detects this situation.
Code examples
Noncompliant code example
try {
// ...
} catch (ExceptionClass ex) { // Noncompliant
//...
}
Compliant solution
try {
// ...
} catch (ExceptionClass &ex) {
//...
}
Resources
Standards
External coding guidelines
Related rules
- S1035 - An exception object should not have a pointer type