nam*_*olk 3 java static exception-handling
我有两个关于静态块和常量的问题,下面的代码.
我想知道为什么会这样?
代码:
public class TestStaticblock {
static{
try {
// NAME = dummyStringValue() + NAME_APPENDER; // Cannot reference a field before it is defined
// NAME = dummyStringValue() + getNameAppender(); // This is OK
NAME = dummyStringValue();
} catch (Exception e) {
NAME = null; // The final field NAME may already have been assigned
}
}
private static String dummyStringValue() throws Exception{
return "dummy";
}
private static String getNameAppender() throws Exception{
return NAME_APPENDER;
}
private static final String NAME; // If I comment Catch it says "The blank final field NAME may not have been initialized"
private static String NAME_APPENDER = "appender";
}
Run Code Online (Sandbox Code Playgroud)
您只能分配NAME
一次(因为它final
).将结果分配给临时变量,然后分配给NAME
(并且不要以静默方式吞下Exception
s).就像是,
static {
String temp = null;
try {
temp = dummyStringValue();
} catch (Exception e) {
e.printStackTrace();
}
NAME = temp;
}
Run Code Online (Sandbox Code Playgroud)
您无法分配NAME
当前方式的原因是编译器执行静态程序分析(特别是数据流分析)并检测到可能存在未分配NAME的代码路径.因为NAME是final
,这是一个编译错误.