Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Removed NCCE because it does not apply to this rule

...

Code Block
bgColor#FFcccc
langcpp
#include <exception>
#include <iostream>
 
struct S : std::exception {
  const char *what() const noexcept override {
    return "My custom exception";
  }
};
 
void f() {
  try {
    throw S();
  } catch (std::exception e) {
    std::cout << e.what() << std::endl;
  }
}

Noncompliant Code Example

In this noncompliant code example, the variable declared by the exception-declaration is an lvalue pointer. Unfortunately the lifetime of the temporary object does not extend to beyond the exception declaration, leaving a dangling pointer. This violates EXP54-CPP. Do not access an object outside of its lifetime.

Code Block
bgColor#FFcccc
langcpp
#include <exception>
#include <iostream>
 
struct S : std::exception {
  const char *what() const noexcept override {
    return "My custom exception";
  }
};
 
void f() {
  try {
    S s;
    throw &s;
  } catch (std::exception* e) {
    std::cout << e->what() << std::endl;
  }
}

Compliant Solution

In this compliant solution, the variable declared by the exception-declaration is an lvalue reference. The call to what() results in executing S::what() instead of std::exception::what().

...