Is it safe to declare the following function noexcept
even though v.at(idx)
could theoretically throw a out_of_range
exception, but practically not due to the bounds check?
int get_value_or_default(const std::vector<int>& v, size_t idx) noexcept { if (idx >= v.size()) { return -1; } return v.at(idx); }
When an exception is thrown from a function that is declared noexcept or noexcept(true) , std::terminate is invoked. When an exception is thrown from a function declared as throw() in /std:c++14 mode, the result is undefined behavior. No specific function is invoked.
Function can be declared 'noexcept'. If code isn't supposed to cause any exceptions, it should be marked by using the noexcept specifier. This annotation helps to simplify error handling on the client code side, and enables the compiler to do more optimizations.
What is you definition of "safe"? If you throw an exception in a function marked asnoexcept
or noexcept(true)
then your program will be terminated (standard 15.4.9)
Whenever an exception is thrown and the search for a handler (15.3) encounters the outermost block of a function with an exception-specification that does not allow the exception, then,
- if the exception-specification is a dynamic-exception-specification, the function std::unexpected() is called (15.5.2),
- otherwise, the function std::terminate() is called (15.5.1).
As long as that is acceptable then you are fine. If you can not tolerate the program terminating then it is not safe.
It is safe. Declaring a function noexcept
would result in immediate program termination (by a call to terminate()
) if an exception occurs. As long as no exception is thrown everything is fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With