c++exceptioncompilationtagsnoexcept

Why is it allowed to throw an exception inside a noexcept-tagged function?


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?


Solution

  • 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:

    double f(double );
    double compute(double x, double y) noexcept
    {
        return x / f(y);
    } 
    

    Can f throw? Can't say.