Suppose I have a function which may call std::terminate
:
int my_fun(int i) noexcept {
if(i==0) std::terminate();
return 3/i;
}
Am I allowed to declare this noexcept
? Nothing is 'thrown' as far as I can tell...
CodePudding user response:
The effect of specifying noexcept
is that you declared the method to not throw. In other words, it is a non-throwing function. When an excpetion is thrown nevertheless then std::terminate
is called. From cppreference:
Non-throwing functions are permitted to call potentially-throwing functions. Whenever an exception is thrown and the search for a handler encounters the outermost block of a non-throwing function, the function
std::terminate
orstd::unexpected
(until C 17) is called:
Hence, you could even throw an exception in my_fun
, it would call std::terminate
as well. noexcept
just means that the exception will not travel up the call stack from my_fun
.
CodePudding user response:
You are correct and can safely define your function noexcept
.
The function std::terminate
itself is noexcept
and does not throw anything. It just terminates your program, and your program will never reach the return statement or reach the end of the function scope.
As the behaviour of std::terminate()
can be overridden with std::terminate_handler
, it is advised to use std::abort()
instead, to ensure proper abortion of your program.
If you would invoke a function that throws an exception, this would be checked at the end of your function scope, in which it will terminate your program.