Back to questions
JuniorTheoryCommon
What happens when this program runs?
#include <iostream>
#include <stdexcept>
void check_age(int age) noexcept {
if (age < 0) {
throw std::invalid_argument("negative age");
}
}
int main() {
try { check_age(-1); }
catch (const std::exception&) { std::cout << "caught"; }
}The program calls std::terminate: check_age is noexcept
- Expecting
caught: an exception that would leave anoexceptfunction callsstd::terminateinstead, so no outer handler sees it. - Expecting a compile error: the compiler does not enforce
noexcept; GCC and Clang only warn, and the program builds.
- What would the program print if
check_agecaught its own exception inside atryblock? - Why is a function that may fail usually not marked
noexcept?