Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

MISRA.CATCH.BY_VALUE

Exception 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.

Rationale

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.

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
}