Why is it allowed to throw an exception inside a n

2019-06-18 20:00发布

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?

2条回答
老娘就宠你
2楼-- · 2019-06-18 20:23

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.

查看更多
小情绪 Triste *
3楼-- · 2019-06-18 20:24

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.

// The compiler does not check the `noexcept` specification at compile time.
void f() noexcept // Promises to not throw any exception
{
    throw runtime_error("error"); // Violates the exception specification
}

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.

查看更多
登录 后发表回答