Main Content
MISRA C++:2008 Rule 15-3-5
A class type exception shall always be caught by reference
Description
Rule Definition
A class type exception shall always be caught by reference.
Rationale
If a class type exception is caught by value, the exception object might be sliced. For instance:
class baseException(); class derivedException : public baseException {}; void foo() { try { //... throw derivedException(); } catch (baseException e) { //slices the thrown exception //... } }
foo()
catches the derivedException
object, you might expect the object to remain a derivedException
object.
Because the object is caught by value, it is sliced to a baseException
object. Unintended object slicing risks unexpected code behavior at runtime. To avoid object
slicing, catch class type exceptions by reference or const
reference.
Polyspace Implementation
Polyspace® flags catch statements where class type exceptions are caught by value.
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 R2013b