简体   繁体   English

如何从使用花括号初始化的对象中捕获异常引发?

[英]How can I catch an exception throw from an object initialized with curly braces?

I'm confronted to a problem. 我遇到了一个问题。 I have this : 我有这个 :

int main()
{
    try
    {
        Class A obj;
    } 
    catch()
    {
     ...
    }
}

class B
{
    public:
        B(){throw an exception there from .cpp};
        ~B();
};

class A
{
    public:
        A();
        ~A();

     private:
        B objB{} // <=== Exception from there, how can I catch it ?
}

As you can see, I don't have any idea how can I get the exception when I initialize an object with curly braces from the header file. 如您所见,我不知道在头文件中使用花括号初始化对象时如何获取异常。

Thank you :) 谢谢 :)

This live example demonstrates the technique of function-level try blocks. 这个实时示例演示了功能级try块的技术。

A()
try {
   /* code */
} catch( exception e ) {
  throw e;
}

note, however, that you must throw an exception if the above construct catches something. 但是请注意,如果上述构造捕获了某些内容,则必须抛出异常。 It need not be the same exception. 不必是相同的例外。 This is because the construction of A has failed (the exception has bypassed parts of the construction of A , and/or some subobject of A had its constructor terminated), and the only way to exit a constructor with a failed construction is via a throw . 这是因为A的构造失败了(该异常绕过了A的构造的一部分,和/或A某些子对象终止了其构造函数),退出构造失败的构造函数的唯一方法是通过throw

I think this is not possible as such. 我认为这是不可能的。 Indeed, it is very similar to Avoid calling constructor of member variable and would leave the objB member of A not constructed. 确实,这与避免调用成员变量的构造函数非常相似,并且会导致AobjB成员未构造。 A solution is to split the constructor of B in two steps: 一个解决方案是将B的构造函数分为两个步骤:

  1. A default constructor that does nothing 不执行任何操作的默认构造函数
  2. A initialize method which trow the exception. 引发异常的initialize方法。 You can pass the braces to that method. 您可以将花括号传递给该方法。
  3. B check that is is properly initialized before doing anything else. B检查是否已正确初始化,然后再执行其他操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM