简体   繁体   English

确保在构造函数抛出异常时初始化最终变量

[英]Making sure that a final variable is initialized when a constructor throws an exception

I have a final member data:我有一个最终的会员数据:

public final Foo foo;

in the constructor, foo is initialized as follow:在构造函数中, foo被初始化如下:

foo = new Foo();

Now, unfortunately, Foo's constructor might throw an exception:现在,不幸的是,Foo 的构造函数可能会抛出异常:

try {
    foo = new Foo();
} catch (Exception e) {
    e.printStackTrace();
}

But now compiler complains that foo might not be initialized, which is true if Foo's constructor throws an exception.但是现在编译器抱怨 foo 可能没有被初始化,如果 Foo 的构造函数抛出异常,这是真的。 But if I put foo = null inside the catch braces, it complains that foo might have been initialized.但是,如果我将foo = null放在 catch 括号内,它会抱怨 foo 可能已被初始化。

Foo is a third-party library that I cannot modify. Foo 是我无法修改的第三方库。

So, what's the most graceful way of handling this?那么,处理这个问题最优雅的方法是什么?

foo = createFoo();

...


private static Foo createFoo() {
    try {
        return new Foo();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

I make no comment about whether it makes sense to continue with construction of your outer object if the inner object's constructor has failed...如果内部对象的构造函数失败,我不评论继续构建外部 object 是否有意义......

final Foo foo ;
Foo foo_temp = null ;
try {
    foo_temp = new Foo();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    foo = foo_temp ;
}

Maybe I don't understand, but I don't get the error.也许我不明白,但我没有得到错误。 Note that ConTest's constructor throws the exception that Foo raises.请注意,ConTest 的构造函数抛出 Foo 引发的异常。 This to me is most elegant (to answer your question.) If Foo fails to initialize, isn't something terribly wrong?这对我来说是最优雅的(回答你的问题。)如果 Foo 无法初始化,是不是出了什么大问题?

ConTest.java:竞赛.java:

   public class ConTest {
       public final Foo foo;
       public ConTest() throws Exception {
           foo = new Foo(3);
       }
   }

Foo.java: Foo.java:

   public class Foo {
       public Foo(int i) throws Exception {
           if (i < 0) throw new Exception("yah");
       }
   }

and it all compiles fine.一切都很好。

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

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