This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 18.3.2 - An exception of class type shall be caught by const reference or reference
Category: Required
Analysis: Decidable,Single Translation Unit
Rationale
Slicing occurs if the exception object is of a derived class and it is caught by value as the base class, which means that information unique to
the derived class’s members is lost. Slicing does not occur when the exception is caught by reference.
Exception objects may be shared between threads, such as when an exception is thrown from std::shared_future. In this case, catching
by const reference reduces the chance of data races.
Example
try
{
mayThrow();
}
catch ( std::runtime_error e ) // Non-compliant - slicing occurs
{
}
catch ( std::exception const & e ) // Compliant - exception object is complete
{
}
Copyright The MISRA Consortium Limited © 2023