AutosarC++17_03-A15.1.3

All thrown exceptions should be unique

Required inputs: IR

Rationale

Defining unique exceptions in the project significantly simplifies debug process.

An exception is considered to be unique if at least one of the following conditions isfulfilled:

  • The type of the exception does not occur in any other place in the project
  • The error message (i.e. message itself, error code, etc.) of the exception doesnot occur in any other place in the project
Example
//% $Id: A15-1-3.cpp 271752 2017-03-23 12:07:07Z piotr.tanski $
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
static std::string composeMessage(const char *file, const char *func,
                          std::int32_t line,
                          const std::string &message) noexcept {
std::stringstream s;
s << "(" << file << ", " << func << ":" << line << "): " << message;
return s.str();
}
void f1() {
// ...
throw std::logic_error("Error");
}
void f2() {
// ...
throw std::logic_error("Error"); // Non-compliant - both exception type and
                           // error message are not unique
}
void f3() {
// ...
throw std::invalid_argument("Error"); // Compliant - exception type is unique
}
void f4() noexcept(false) {
// ...
throw std::logic_error("f3(): preconditions were not met"); // Compliant -
                                                      // error
                                                      // message is
                                                      // unique
}
void f5() noexcept(false) {
// ...
throw std::logic_error(composeMessage(
__FILE__, __func__, __LINE__,
"postconditions were not met")); // Compliant - error message is unique
}
void f6() noexcept {
try {
f1();
f2();
f3();
}

catch (std::invalid_argument &e) {
std::cout << e.what() << ’\n’; // Only f3() throws this type of
                           // exception, it is easy to deduce which
                           // function threw
}

catch (std::logic_error &e) {
std::cout << e.what() << ’\n’; // f1() and f2() throw exactly the same
                           // exceptions, unable to deduce which
                           // function threw
}

try {
f4();
f5();
}

catch (std::logic_error &e) {
std::cout << e.what() << ’\n’; // Debugging process simplified, because
                           // of unique error message it is known
                           // which function threw
}
}
See Also
  • Effective Java 2nd Edition [14]: Item 63: Include failure-capture information in detail messages

Possible Messages

Key

Text

Severity

Disabled

throwing_duplicate

All thrown exceptions should be unique.

None

False

Options