AutosarC++18_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 should 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 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#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