Rule Definition
If a class type exception object is caught by value, slicing occurs. That is, if the exception object is of a derived class and is caught as the base, only the base class’s functions (including virtual functions) can be called. Also, any additional member data in the derived class cannot be accessed. If the exception is caught by reference, slicing does not occur.
This leads to an issue that the actual and more specific exception is not thrown losing valuable exception information and leading to incorrect error recovery.
Remediation
Catch the exception object by reference using &operator.
Violation Code Sample
// base class for exceptions
class ExpBase
{ public:
virtual const char_t *who ( )
{ return "base";
};
};
class ExpD1: public ExpBase
{ public:
virtual const char_t *who ( )
{ return "type 1 exception"; };
};
class ExpD2: public ExpBase
{ public:
virtual const char_t *who ( )
{ return "type 2 exception";
};
};
_________________________________
try
{
// ...
throw ExpD1 ( );
// ...
throw ExpBase ( );
}
// Using the definitions above ...
catch ( ExpBase b ) // Non-compliant - derived type objects will be
// caught as the base type
{
b.who(); // Will always be "base"
throw b; // The exception re-thrown is of the base class,
// not the original exception type
}
Fixed Code Sample
try
{
// ...
throw ExpD1 ( );
// ...
throw ExpBase ( );
}
catch ( ExpBase &b ) // Compliant – exceptions caught by reference
{
// ...
b.who(); // "base", "type 1 exception" or "type 2 exception"
// depending upon the type of the thrown object
}
___________________________________________________________________
The exception to the rule:
try
{
// ...
throw ExpD1 ( );
// ...
throw ExpBase ( );
}
catch (ExpBase) // No-violation
{
b.who();
}
Reference
Standards References:
MISRA C++ 2008, Rule 15–3–5: A class type exception shall always be caught by reference.
OMG CWE - 397
Related Technologies
Technical Criterion
CWE-397 - Declaration of Throws for Generic Exception
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.