Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 方法引发的未处理异常不会阻止编译_Java_Methods_Exception Handling - Fatal编程技术网

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
是一种好的做法,还是只按正确的顺序处理它们?