我有一个要初始化的变量,该变量来自有异常的类。
因此,如果我执行类似 ConfigurationProvider reader = configurationReader.configurationProvider() 的操作,.configurationProvider() 部分会显示红线,告知异常在 IntelliJ 中未处理。
所以我尝试在 try/catch block 中捕获它,如下所示:
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;
}
现在,正如您在注释中看到的,reader 下有一条红线,表示该变量尚未初始化。我理解为什么编译器会提示,因为它可能会跳过 try 并转到 catch block 。我会尝试删除 catch block ,但我也不能这样做,因为我必须处理异常。这种情况我能做什么?任何帮助将不胜感激。
最佳答案
如果抛出并捕获异常,则有一条 reader
未初始化的执行路径。如果尝试初始化 Reader 时抛出异常,您甚至不应该尝试使用它。
只有当没有抛出异常时,您才应该使用它并尝试返回一个值。将 catch
block 后面的所有代码放入初始化之后的 try
block 中。
try {
reader = configurationReader.configurationProvider();
Properties config = reader.getConfiguration(configName);
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;
} catch (Exception e){
e.printStackTrace();
}
现在,编译器会提示并非所有路径都返回值,在抛出异常时,这种情况就是如此。要么重新抛出异常,要么返回一些东西来表明返回值无效。重新抛出异常还需要在您的方法上使用 throws
子句。
} catch (Exception e){
e.printStackTrace();
throw e;
// OR
return null;
}
关于java - try/catch 中未初始化的变量,带有未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55717882/