Why is my exception still being thrown after being caught?

c++, c++11, exception

Solution

Constructors with function try blocks (like what you have for `S`) automatically rethrow any exceptions caught by the `catch` block. Consequently, after the `catch` catches the exception, it rethrows it. This behavior is different from normal `catch` handlers, which don't do this. I think the rationale is that if construction of a data member or base class fails, the object has failed to construct. The purpose of the `catch` handler is just to do any extra cleanup before the exception propagates outward.

Hope this helps!

Problem

I have the following code where a variable is being initialized with the result of a function call. This function throws so I set up a try-catch to catch the exception. For some reason the exception is still showing up on the screen even after the catch clause runs. ``` #include <iostream> #include <stdexcept> int f() { throw std::invalid_argument("threw"); return 50; } struct S { S() try : r(f()) { std::cout << "works"; } catch(const std::invalid_argument&) { std::cout << "fails"; } int r; }; int main() { S s; } ``` This code prints "fails" after showing the exception: ``` terminate called after throwing an instance of 'std::invalid_argument' what(): threw ``` Why is the exception still thrown? I have the same code set up in main and it works without fail: ``` int main() { try { throw std::invalid_argument("blah"); } catch(const std::invalid_argument&) { } } ``` So why does it fail when being used in an initializer list?

Original source