Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a theoretically, but not practically, throwing function be declared noexcept?

Tags:

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); } 
like image 579
j00hi Avatar asked Aug 04 '15 12:08

j00hi


People also ask

What happens if a Noexcept function throws?

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.

Can be declared Noexcept?

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.


2 Answers

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.

like image 136
NathanOliver Avatar answered Sep 18 '22 17:09

NathanOliver


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.

like image 34
Matthias J. Sax Avatar answered Sep 17 '22 17:09

Matthias J. Sax