What happens when an exception is thrown while computing a constexpr?

Viewed 1973

When computing constant expressions to initialize a constexpr it is possible to throw exceptions. For example here is an example where the computation of a constant expression is guarded against overflow:

#include <iostream>
#include <stdexcept>

constexpr int g(int n, int n0, int n1) {
    return n == 0? n1: g(n - 1, n1, n0 + n1);
}

constexpr int f(int n) {
    return n < 42? g(n, 0, 1): throw std::out_of_range("too big");
}

int main()
{
    try {
        constexpr int f41 = f(41); // OK: constexpr
        int           f43 = f(43); // OK: throws an exception
        constexpr int f42 = f(42); // not OK but what happens?
    }
    catch (std::exception const& ex) {
        std::cout << "ERROR: " << ex.what() << "\n";
    }
}

The first call to f() just shows that a constexpr can be computed. The second call to f() isn't used to initialize a constexpr and throws a run-time exception. The third call to f() is used to initialize a constexpr but that point won't ever reached because an exception is thrown. However, what should happen in this case? I would expect the handler in the catch-clause is executed but both gcc and clang produce a compile-time error.

1 Answers
Related