How does noexcept work in c++?

Question:

What does the noexcept specification do? I thought that it would not allow the function to throw an exception, but it is not, the function:

int Foo() noexcept
{
    throw std::runtime_error("error");
    return 0;
}

compiles, its call falls quietly, which means the exception has been thrown. noexcept didn't change anything.

Answer:

The noexcept provides a compile-time guarantee that no exception will be thrown from the function. However, this guarantee is equivalent to wrapping the body of the function in a try…catch block with a call to ::std::terminate :

int Foo() noexcept
{
    try
    {
        throw std::runtime_error("error");
    }
    catch(...)
    {
        ::std::terminate();
    }
}

It is only in the simplest cases that compilers can determine what exceptions are really thrown in the body of a function and optimize their catching. The idea was that the calling code could do the optimization. But in practice, all this does not work and there is actually no control over exceptions during compilation, especially after throwing out exception specifiers, in c++.

Scroll to Top