为什么被捕后我的异常仍被抛出?

0x4*_*2D2 6 c++ exception-handling c++11

我有以下代码,其中一个变量正在使用函数调用的结果进行初始化.这个函数抛出所以我设置了一个try-catch来捕获异常.由于某种原因,即使在catch子句运行后,异常仍会出现在屏幕上.

#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;
}
Run Code Online (Sandbox Code Playgroud)

显示异常后,此代码打印"失败":

terminate called after throwing an instance of 'std::invalid_argument'
what():  threw
Run Code Online (Sandbox Code Playgroud)

为什么异常仍然被抛出?我在main中设置了相同的代码,它可以正常工作:

int main()
{
    try { throw std::invalid_argument("blah"); }
    catch(const std::invalid_argument&) { }
}
Run Code Online (Sandbox Code Playgroud)

那么为什么它在初始化列表中使用时会失败呢?

tem*_*def 14

具有函数try块的构造函数(就像你所拥有的那样S)会自动重新抛出catch块所捕获的任何异常.因此,在catch捕获异常后,它会重新抛出异常.此行为与正常catch处理程序不同,后者不执行此操作.我认为基本原理是,如果构造数据成员或基类失败,则该对象无法构造.catch处理程序的目的只是在异常向外传播之前进行任何额外的清理.

希望这可以帮助!