AutosarC++17_03-A15.1.1

Only instances of types derived from std::exception shall be thrown

Required inputs: IR

Rationale

If an object that inherits from std::exception is thrown, there’s a guarantee that it serves to document the cause of an exception in an unified way. Also, "it makes your code easier to learn and re-use, because it matches established conventions with which programmers are already familiar.". [Effective Java 2nd Edition [14]] This means that only standard library exceptions or user-defined exceptions that inherit from std::exception base class shall be used for exceptions.

Note that direct instances of std::exception are not to be thrown as they can not be unique.

Example
//% $Id: A15-1-1.cpp 271715 2017-03-23 10:13:51Z piotr.tanski $
#include <memory>
#include <stdexcept>
class A {
// Implementation
};
class MyException : public std::logic_error {
public:
using std::logic_error::logic_error;
// Implementation
};
void f1() {
throw - 1; // Non-compliant - integer literal thrown
}
void f2() {
throw nullptr; // Non-compliant - null-pointer-constant thrown
}
void f3() {
throw A(); // Non-compliant - user-defined type that does not inherit from
     // std::exception thrown
}
void f4() {
throw std::logic_error{
"Logic Error"}; // Compliant - std library exception thrown
}
void f5() {
throw MyException{"Logic Error"}; // Compliant - user-defined type that
                            // inherits from std::exception thrown
}
void f6() {
throw std::make_shared<std::exception>(
std::logic_error("Logic Error")); // Non-compliant - shared_ptr does
                                // not inherit from std::exception
}
void f7() {
try {
f6();
}

catch (std::exception &e) // An exception of
                    // std::shared_ptr<std::exception> type will not
                    // be caught here
{
// Handle an exception
} catch (std::shared_ptr<std::exception> &e) // An exception of
// std::shared_ptr<std::exception>
// type will be caught here, but
// unable to access
// std::logic_error information
{
// Handle an exception
}
}
See Also
  • HIC++ v4.0 [8]: 15.1.1 Only use instances of std::exception for exceptions
  • C++ Core Guidelines [10]: E.14: Use purpose-designed user-defined types as exceptions (not built-in types)
  • Effective Java 2nd Edition [14]: Item 60: Favor the use of standard exceptions

Possible Messages

Key

Text

Severity

Disabled

throwing_std_exception

Only instances of types derived from std::exception shall be thrown.

None

False

Options