Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does calling std::terminate violate noexcept?

Tags:

c++

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...

like image 487
Joe Todd Avatar asked Jan 23 '26 07:01

Joe Todd


2 Answers

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.

like image 103
Emmef Avatar answered Jan 25 '26 21:01

Emmef


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 or std::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.

like image 20
463035818_is_not_a_number Avatar answered Jan 25 '26 21:01

463035818_is_not_a_number



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!