Eternal
Eternal

Reputation: 2959

When can the standard library functions throw exceptions?

I'm having trouble understanding which functions from the standard library can throw exceptions, and if so which and when.

Some functions are noexcept, in which case ok they don't, but if I look for example at std::string::operator[](): https://en.cppreference.com/w/cpp/string/basic_string/operator_at, the operator is not noexcept yet the page says nothing about exceptions (and same here so it should have nothing to do with std::basic_string being a template).

Can I assume that if no exception is listed on a page then it means that the function cannot throw (but was not marked as noexcept for some reason)? Or does it mean the function can throw implementation-defined exceptions? And when exceptions are listed, are they the only ones that can be thrown?

Edit:

Upvotes: 3

Views: 213

Answers (1)

BoP
BoP

Reputation: 3160

Sometimes you have to read between the lines.

The string operator[] has a precondition that the index must be valid. cppreference says:

If pos > size(), the behavior is undefined.

Undefined behavior includes throwing exceptions. And, in fact, some implementations will throw an out-of-range exception in debug mode.

The math functions, like std::abs, originally come from the C library. Even though the C library doesn't throw exceptions, it also doesn't say noexcept for any of the functions, so to be compatible neither does C++.

Upvotes: 1

Related Questions