Consider this artificial example.
Two identical destructors, one catches the exception inside function style try/catch, one scope based try/catch.
#include <iostream>
struct A {
~A() noexcept try {
throw std::runtime_error("~A");
} catch (std::exception const &e) {
std::cout<<__LINE__<<" "<<e.what()<<std::endl;
}
};
struct B {
~B() noexcept {
try {
throw std::runtime_error("~B");
} catch (std::exception const &e) {
std::cout<<__LINE__<<" "<<e.what()<<std::endl;
}
}
};
int main() try {
// A a; // std::terminate is called, exception not caught at line 26. The try-catch block in main is not relevant.
B b;
return 0;
} catch (std::exception const &e) {
std::cout<<__LINE__<<" "<<e.what()<<std::endl;
}
Godbolt link: example
So class B
's destructor catches the exception and prints: 16 ~B
Were in case of class A
it calls terminates and prints:
terminate called after throwing an instance of 'std::runtime_error'
what(): ~A
7 ~A
May someone hint thy is this happening? (seems implicit rethrow at the end of function style try/catch, both on clang and GCC) Does standard somehow specifying this behaviour? Any quote/link may be very helpfull. Thanks in advace.