【发布时间】:2019-04-16 23:29:05
【问题描述】:
我有一个来自异常类的变量要初始化。
因此,如果我执行 ConfigurationProvider reader = configurationReader.configurationProvider() 之类的操作,.configurationProvider() 部分会显示红线,说明 IntelliJ 中未处理异常。
所以我尝试在 try/catch 块中捕获它,如下所示:
private String getConfigValue(ConfigurationProviderConfiguration configurationReader, String configName) {
String value = null;
ConfigurationProvider reader;
try {
reader = configurationReader.configurationProvider();
} catch (Exception e){
e.printStackTrace();
}
Properties config = reader.getConfiguration(configName); //Now, there is a red line under reader saying the variable might not have been initialized
if (config == null) {
LOGGER.warn("The configuration for " + configName + " cannot be found.");
}else{
value = config.getValue();
if (value == null) {
LOGGER.warn("The configuration for " + configName + " cannot be found.");
}
}
return value;
}
现在您可以在评论中看到,读者下方有一条红线表示变量未初始化。我理解为什么编译器会抱怨,因为它可能会跳过 try 并转到 catch 块。我会尝试删除 catch 块,但我也不能这样做,因为我必须处理异常。在这种情况下我能做什么?任何帮助将不胜感激。
【问题讨论】:
-
初始化它:
ConfigurationProvider reader = null; -
将使用阅读器的代码也放入 try 块中。
-
@CardinalSystem 然后在执行到该行时产生空指针异常。
标签: java variables exception initialization try-catch