如何处理抛出检查异常的静态final field initializer [英] How to handle a static final field initializer that throws checked exception
问题描述
static final
字段和一个声明为引发检查异常的initializer语句。通常,它看起来像这样:public static final ObjectName OBJECT_NAME = new ObjectName(foo:type = bar);
我在这里的问题是, ObjectName
构造函数可能会抛出各种检查的异常,我不在乎(因为我知道我的名字是有效的,如果它不是崩溃的话,这是很好的)。 java编译器不会让我忽略这个(因为它是一个被检查的异常),我不想诉诸:
public static final ObjectName OBJECT_NAME;
static {
try {
OBJECT_NAME = new ObjectName(foo:type = bar);
} catch(final Exception ex){
throw new RuntimeException(无法在静态块中创建ObjectName实例,ex);
}
}
因为静态块真的很难阅读。有没有人有一个建议,如何以一个漂亮,干净的方式处理这种情况?
如果你不喜欢静态块(有些人不),那么另一种方法是使用静态方法。 IIRC,Josh Bloch推荐这个(显然不是在有效的Java快速检查)。
public static final ObjectName OBJECT_NAME = createObjectName( FOO:类型=栏);
private static ObjectName createObjectName(final String name){
try {
return new ObjectName(name);
} catch(final SomeException exc){
throw new Error(exc);
}
}
或:
public static final ObjectName OBJECT_NAME = createObjectName();
private static ObjectName createObjectName(){
try {
return new ObjectName(foo:type = bar);
} catch(final SomeException exc){
throw new Error(exc);
}
}
(已编辑:修正了从方法返回的第二个示例分配 static
。)
I am facing a use case where I would like to declare a static final
field with an initializer statement that is declared to throw a checked exception. Typically, it'd look like this:
public static final ObjectName OBJECT_NAME = new ObjectName("foo:type=bar");
The issue I have here is that the ObjectName
constructor may throw various checked exceptions, which I don't care about (because I'd know my name is valid, and it's allright if it miserably crashes in case it's not). The java compiler won't let me just ignore this (as it's a checked exception), and I would prefer not to resort to:
public static final ObjectName OBJECT_NAME; static{ try{ OBJECT_NAME = new ObjectName("foo:type=bar"); }catch(final Exception ex){ throw new RuntimeException("Failed to create ObjectName instance in static block.",ex); } }
Because static blocks are really, really difficult to read. Does anyone have a suggestion on how to handle this case in a nice, clean way?
If you don't like static blocks (some people don't) then an alternative is to use a static method. IIRC, Josh Bloch recommended this (apparently not in Effective Java on quick inspection).
public static final ObjectName OBJECT_NAME = createObjectName("foo:type=bar");
private static ObjectName createObjectName(final String name) {
try {
return new ObjectName(name);
} catch (final SomeException exc) {
throw new Error(exc);
}
}
Or:
public static final ObjectName OBJECT_NAME = createObjectName();
private static ObjectName createObjectName() {
try {
return new ObjectName("foo:type=bar");
} catch (final SomeException exc) {
throw new Error(exc);
}
}
(Edited: Corrected second example to return from method instead of assign the static
.)
这篇关于如何处理抛出检查异常的静态final field initializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!