Search code examples
c++noexcept

can floating point multiplication throw an exception in C++?


Is this possible? I don't think it is, but I don't know if this is something the standard would say, or if it's implementation defined? I'm asking because I'm wondering whether it's safe or worth it to mark a constexpr function like this noexcept

EX:

constexpr double to_meters(double y) noexcept? {
  return y * 10;
}
constexpr double x = to_meters(y); // Clang-Tidy warns about possible exception without noexcept

Solution

  • The language definition doesn't give you any guarantees here, but since virtually every implementation (that is, there are none I know of that don't) implements IEEE-754 math, which does not throw exceptions, it's not something I'd worry about. And more generally, a floating-point math package that throws exceptions would have had to be written with C++ in mind; that's highly unlikely.

    However, you may well get messages when a floating-point error occurs that refer to a "floating-point exception"; that's a floating-point exception, not a C++ exception, and it has nothing to do with C++ exceptions. It's a runtime error, with a peculiar name.