构造函数作为一个函数try块 - 异常中止程序 [英] Constructor as a function try block - Exception aborts program

查看:118
本文介绍了构造函数作为一个函数try块 - 异常中止程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是否是编译器的问题,或者如果我做错了。我使用Visual Studio 2013编译器。



我有一个类,我需要在我的构造函数初始化列表中获取大量的资源,其中大部分可以抛出异常。我在一个函数try块中封装了成员初始化列表,并捕获了异常。但是我的程序仍然中止,即使catch子句不重新抛出异常。我不允许发布实际的代码。所以我已经复制这个等效的演示代码的问题。有人可以帮我解决这个问题吗?

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


int main(){
A obj;
}

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



另一方面,如果我在一个try-catch块中的main()中包装对象的构造,那么异常被正确捕获,程序正常终止。 / p>

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

解决方案

p>有相关资料



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



基本上即使你不抛出你的catch块,异常也会自动重新生成


如果处理程序主体包含语句throw;那么catch
块将明显地重新抛出任何异常A :: A()或B :: B()有
发出。不太明显,但在标准中清楚地说明的是
,如果catch块不抛出(重新抛出原来的
异常,或者抛出一些新的东西),并且控制到达$ b的结尾$ b catch块的构造函数或析构函数,那么原来的
异常会自动被重绘。



I am not sure if this is a issue with the compiler or if I am doing something wrong. I am using Visual Studio 2013 compiler.

I have a class where I need to acquire significant amount of resources in my constructor initializer list most of which can throw an exception. I wrapped up the member initializer list in a function try block and caught the exception there. But my program still aborts even though the catch clause doesn't re-throw the exception. I am not allowed to post the actual code. So I have reproduced the issue with this equivalent demo code. Can someone please help me address this?

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

On executing this code I get a windows alert "abort() has been called". So I guess the system is treating this as an uncaught exception and calling terminate().

On the other hand if I wrap the construction of the object in main() in a try-catch block then the exception is caught properly and the program terminates normally.

Can someone please tell me if I am doing something wrong here?

解决方案

There's a relevant gotw

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

Basically even if you don't throw in your catch block, the exception will automatically be rethrown

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.

这篇关于构造函数作为一个函数try块 - 异常中止程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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