Java 方法引发的未处理异常不会阻止编译
我在一个类中有两个方法:Java 方法引发的未处理异常不会阻止编译,java,methods,exception-handling,Java,Methods,Exception Handling,我在一个类中有两个方法: public String getConsumerKey() throws FileNotFoundException, IOException { String consumerKey; consumerKey = getPropertyValueOrNull(getConfigPath(CONSUMERVALUESCONFIGNAME),"consumer_key"); return consumerKey; } private
public String getConsumerKey() throws FileNotFoundException, IOException
{
String consumerKey;
consumerKey = getPropertyValueOrNull(getConfigPath(CONSUMERVALUESCONFIGNAME),"consumer_key");
return consumerKey;
}
private String getPropertyValueOrNull(String path, String key) throws FileNotFoundException, IOException
{
Properties prop = new Properties();
String value = null;
// load a properties file
prop.load(new FileInputStream(path));
value = prop.getProperty(key);
if ( value == null || value.isEmpty())
{
value = null;
}
return value;
}
我从main方法调用getCosumerKey()
,如下所示:
public static void main(String[] args)
{
try {
MyClass.getInstance().getConsumerKey();
} catch (IOException e) {
e.printStackTrace();
}
}
当我运行这段代码时,除了得到一个FileNotFoundException外,没有任何问题。当我试图添加一个catch块来处理FileNotFoundException时,我得到一个错误,说异常已经从IOException catch块处理了
编译器不应该阻止我运行代码吗?为什么编译器不让我处理异常呢?
FileNotFoundException
是IOException
的子类。如果要单独处理它,必须首先捕获它。可以将公共字符串getConsumerKey()抛出FileNotFoundException,IOException
更改为公共字符串getConsumerKey()抛出IOException
,因为FileNotFoundException
扩展自IOException
。运行时错误和编译时错误之间存在差异。您得到一个FileNotFoundException
的事实仅仅意味着getConfigPath(CONSUMERVALUESCONFIGNAME)
点不存在,现有代码在捕捉到IOException
时会捕捉到这一点。如果您想处理FNF异常,那么在IOException
块之前需要一个catch块。哦,我明白了,您是对的。因此,您认为从方法中删除throws-FileNotFoundException
并仅保留IOException
是一种好的做法,还是只按正确的顺序处理它们?