Why is my exception still being thrown after being caught?

冷暖自知 提交于 2020-01-22 20:07:26

问题


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?


回答1:


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!




回答2:


From the C++11 Standard, 15.3/15:

The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor.

The reasons are well explained in the GOTW Jerry links under your question, but summarily: imagine if it hadn't rethrown, then the next lines after S s; will presumably attempt to use s despite it never having completed construction, and when s leaves scope the constructor will have arranged a call to the destructor for s - potentially freeing never-initialised pointers, releasing never-taken locks etc..

By way of contrast, if you let the data member be default initialised then assign to it from a try/catch block in the constructor body, the state of the object including bases and data members can potentially be kept in some coherent state: it's up to you as the programmer to decide whether that state's ok - i.e. whether you'll use the try/catch block inside the constructor body, and have later member functions handle a potentially default-constructed data member.



来源:https://stackoverflow.com/questions/20341355/why-is-my-exception-still-being-thrown-after-being-caught

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!