Why is this an issue?
Catching an exception class by value rather than by reference has several bad effects:
- Slicing occurs, yielding an instance of the exception’s base class, rather than the potentially more specific exception class that was actually
thrown. This means that only the base class' functions will be available; any additional data or functionality that is offered by the extended class
will not be accessible.
- Memory is allocated unnecessarily.
- Copying the exception class might potentially throw an exception.
You might also be tempted to catch an exception by pointer, but this causes issues related to the exception lifetime, and should also be avoided.
This situation is detected by rule {rule:cpp:S1035}.
Therefore exception classes should always be caught by reference.
Noncompliant code example
try
{
// ...
}
catch(ExceptionClass ex)
{
//...
}
Compliant solution
try
{
// ...
}
catch(ExceptionClass &ex)
{
//...
}
Resources
- MISRA C++:2008, 15-3-5 - A class type exception shall always be caught by reference
- CERT, ERR61-CPP. - Catch exceptions by lvalue reference
- C++ Core Guidelines
E.15 - Catch exceptions from a hierarchy by reference