Middle+
What happens if an exception is thrown in a function marked as noexcept?
sobes.tech AI
Answer from AI
A call to std::terminate will occur. The standard guarantees that, prior to calling std::terminate, std::unexpected will be called in C++17 and earlier versions, but this behavior was removed in C++20. Therefore, in modern standards (C++20 and above), when an exception is thrown from a function marked noexcept, std::terminate is called immediately.
By default, std::terminate calls abort. The behavior of std::terminate can be modified by calling std::set_terminate.
Example:
#include <iostream>
#include <exception>
void my_terminate_handler() {
std::cerr << "Custom terminate handler called!\n";
std::abort(); // You can call abort or exit
}
void function_noexcept() noexcept {
std::cout << "Inside noexcept function. Throwing exception...\n";
throw std::runtime_error("Something went wrong!"); // Throwing an exception
std::cout << "This line will not be reached.\n";
}
int main() {
std::set_terminate(my_terminate_handler); // Setting custom terminate handler
try {
function_noexcept();
} catch (...) {
// This catch block will not be executed because exception from noexcept
// leads directly to calling terminate.
std::cerr << "Caught an exception (this should not happen for noexcept).\n";
}
std::cout << "End of main (should not be reached).\n";
return 0; // This return will not be reached because main will end via terminate/abort
}
The program output will be approximately:
Inside noexcept function. Throwing exception...
Custom terminate handler called!