MISRA.CATCH.BY_VALUEException object of class type is caught by value. MISRA-C++ Rule 15-3-5 (required): A class type exception shall always be caught by reference.RationaleIf 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. Example// 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 ( ); } 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 } // 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 } |