Does all std functions throw exceptions?

Sep 22, 2021 at 12:43pm
Does all standard functions throw exceptions? Or only the ones that have specs where it's mentioned ?
Last edited on Sep 22, 2021 at 12:43pm
Sep 22, 2021 at 1:00pm
I don't think so. For one c++17 added a lot of noexcept to functions, so it depends to which standard one is compiling against. cppreference is pretty good at documenting all that stuff.
Sep 22, 2021 at 1:08pm
Only when the standard defines that it does. In which case it will be specified under what conditions which exception(s) are thrown.

Last edited on Sep 22, 2021 at 2:08pm
Sep 22, 2021 at 1:26pm
Perfect. Thank you both.
Sep 22, 2021 at 3:38pm
Most functions with narrow contracts that are not marked noexcept potentially throw exceptions. This is because throwing an exception is an option if a library preconditon is violated.

Some implementations use this rule to good effect, throwing exceptions from functions that are called incorrectly in order to avoid more serious problems.

This policy is codified in numbered papers N3248 and N3279.
https://wg21.link/n3279
https://wg21.link/n3248

This rule shouldnt typically change the way you write code because you should not expect your program to violate a library's preconditions or exhibit undefined behavior.
Last edited on Sep 22, 2021 at 10:36pm
Sep 22, 2021 at 5:47pm
Functions from the C standard library shall not throw exceptions (Note: That is, the C library functions can all be treated as if they are marked noexcept. This allows implementations to make performance optimizations based on the absence of exceptions at runtime.),

except when such a function calls a program-supplied function that throws an exception. (Note: The functions qsort() and bsearch() meet this condition.)


and

Destructor operations defined in the C++ standard library shall not throw exceptions. Every destructor in the C++ standard library shall behave as if it had a non-throwing exception specification.


https://eel.is/c++draft/res.on.exception.handling

Sep 22, 2021 at 10:50pm
Amended my post to say "most functions" instead of "all functions", thanks for the correction.

Essentially the absence of a "throws:" clause in the standard doesn't imply "no exceptions are thrown".
Instead it means "no exceptions are thrown if preconditions are satisfied". All this is covered in the linked papers.
Sep 23, 2021 at 9:12pm
right, a thing to consider is many library functions work with user-defined types. So vector<T, Alloc>::push_back does not have a "Throws" clause, but it will throw if T::T or Alloc::allocate does.
Topic archived. No new replies allowed.