How relevant is the nothrow specification in C++ now?

Question:

Once upon a time in C++ it was possible to specify a nothrow specification for a method/function. Which indicated that the method / function does not throw exceptions.

As a disciplined user, I tried to use this specification in my time. But it soon became clear that during development it is very tedious to keep track of which functions throw an exception and which do not. And I stopped specifying nothrow.

Now there is a project in which, in principle, there is no generation of exceptions. As a result, questions arose.

Questions:

  1. Is nothrow currently supported in the standard?

  2. Is nothrow now recommended in the standard? Or, as is often the case with new C++, it is deprecated.

  3. What is the use of the nothrow specification? Can the compiler generate faster/compact code when using the nothrow specification? Or is there no difference?

  4. Is it possible to immediately tell the compiler that all class methods have the nothrow specification? In order not to mess around with each method and not specify nothrow in it.

Answer:

It is likely that you are talking about throw() , because std::nothrow is a little different. The throw() specification is marked deprecated in C++17 and will be removed from future standards, so its use is not recommended. The modern standard has another specifier: noexcept , the essence of which is to call std::terminate if the exception leaves the function marked with this specifier.

Using noexcept code can turn out better, but the main purpose of this specifier is to define the appropriate interfaces. Therefore, there are no mechanisms that make everything noexcept – every interface must be explicitly marked (with the exception of destructors, which are noexcept by default).

Scroll to Top