TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C++ Coding Standard
Search

Rule:  ERR#014Checked automatically with code checker

Synopsis:Do not catch objects by value
Language:C++
Severity Level:1
Category:Error Handling


Description:

If objects are caught by value, there is a risk the exception will be sliced. See for instance the following example:

class Exception{};
class SpecialException : public Exception {};
 
try {
    throw SpecialException();
} catch (Exception e) {
    cout << "Caught" << typeid(e).name() << endl;
}

A SpecialException is thrown but its parent Exception is caught. We are catching by value, which results in copying the exception. But since we are catching Exception, not SpecialException, Exception‘s copy construcor is called, and we lose the SpecialException part of the object.

The right way to write this would be to use a const reference:

class Exception{};
class SpecialException : public Exception {};
 
try {
    throw SpecialException();
} catch (const Exception& e) {
    cout << "Caught" << typeid(e).name() << endl;
}

This will result in a reference to the original SpecialException.



Literature References:
Knatten