gpt4 book ai didi

Java:创建其构造函数可能引发异常的静态类成员

转载 作者:搜寻专家 更新时间:2023-10-31 08:10:32 24 4
gpt4 key购买 nike

我有一个用于设置 MyClass 的所有实例的静态 setter :

public class MyClass {  
....
protected static final Setter setter = new Setter();
...
}

然而,由于 setter 构造函数抛出异常,因此无法编译:

public class Setter {

public Setter() throws FileNotFoundException {
....
}
}

我该如何解决这个问题?

最佳答案

ExceptionInInitializerError正是为此目的而设计的。这是链接的 Javadoc 中的相关引用:

Signals that an unexpected exception has occurred in a static initializer. An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.

将赋值包装在静态初始化 block 中并进行相应处理。

public class MyClass {  
protected static final Setter setter;

static {
try {
setter = new Setter();
} catch (FileNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
}

关于Java:创建其构造函数可能引发异常的静态类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3247055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com