I'm having a hard time understanding this.
double compute(double x, double y) noexcept
{
if (y == 0)
throw std::domain_error("y is zero");
return x / y;
}
this compiles fine in clang (I haven't checked gcc), but it seems nonsense to me. Why would a compiler allow a noexcept function to contain a throw statement?
What will happen is
std::terminate()
gets triggered, since your exception specification doesn't allow for this to happen (see [except.spec/9]).As to why it's allowed, it's simply not possible to exhaustively check if anything violates the specification. Consider something like:
Can
f
throw? Can't say.It is possible that a function that claims to not throw will in fact throw.
If a
noexcept
function does throw,terminate
is called, thereby enforcing the promise not to throw at run time.Specifying that a function won't throw promises the callers of the non-throwing function that they will never need to deal with exceptions.
Either the function won't throw or the whole program will terminate.