c++ - 构造函数作为函数 try block - 异常中止程序

标签 c++ c++11

我不确定这是编译器的问题还是我做错了什么。我正在使用 Visual Studio 2013 编译器。

我有一个类,我需要在我的构造函数初始化列表中获取大量资源,其中大部分都可能引发异常。我将成员初始值设定项列表包装在一个函数 try block 中,并在那里捕获了异常。但是我的程序仍然中止,即使 catch 子句没有重新抛出异常。我不允许发布实际代码。所以我用这个等效的演示代码重现了这个问题。有人可以帮我解决这个问题吗?

#include <iostream>
using namespace std;
class A{
public:
    A() try : i{ 0 }{ throw 5; }
    catch (...){ cout << "Exception" << endl; }
private:
    int i;
};


int main(){
    A obj;
}

在执行此代码时,我收到一个 Windows 警报“abort() 已被调用”。所以我猜系统将此视为未捕获的异常并调用 terminate()。

另一方面,如果我将 main() 中的对象构造包装在 try-catch block 中,则异常会被正确捕获并且程序正常终止。

如果我在这里做错了什么,有人可以告诉我吗?

最佳答案

有一个相关的gotw

http://gotw.ca/gotw/066.htm

基本上即使你没有抛出你的catch block ,异常也会自动重新抛出

If the handler body contained the statement "throw;" then the catch block would obviously rethrow whatever exception A::A() or B::B() had emitted. What's less obvious, but clearly stated in the standard, is that if the catch block does not throw (either rethrow the original exception, or throw something new), and control reaches the end of the catch block of a constructor or destructor, then the original exception is automatically rethrown.

关于c++ - 构造函数作为函数 try block - 异常中止程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31241648/

相关文章:

c++ - 如何使用 C++ 原子

c++ - 基于模板参数推导利用的 STL 算法名称可解析或未定义

c++ - 如何将多个参数传递给 pcap_loop()/pcap_handler()?

c++ - 我什么时候会在基类中默认(而不是删除)复制和移动操作

c++ - 仅在派生类时才给出 SEG FAULT 的代码!

c++ - 在 C++ 中,seekg 似乎包含 cr 字符,但 read() 会删除它们

c++ - 如何在 C++ 中的两个类之间定义(重载)对称二元运算符,同时考虑 r 值?

c++ - unique_ptr 交换不起作用

c++ - 创建独立控件的好策略 Direct2D

c++ - 单击 MFC 气球工具提示的 "X"关闭按钮会发送什么事件?