为什么我的异常在被捕后仍然被抛出? [英] Why is my exception still being thrown after being caught?

查看:194
本文介绍了为什么我的异常在被捕后仍然被抛出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

此代码在显示异常后显示failed:

This code prints "fails" after showing the exception:


terminate called after throwing an instance of 'std::invalid_argument'
what():  threw


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

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&) { }
}

推荐答案

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

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.

希望这有助于!

这篇关于为什么我的异常在被捕后仍然被抛出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆