Java 尝试捕获vs尝试使用资源
为什么在Java 尝试捕获vs尝试使用资源,java,exception,Java,Exception,为什么在readFile2()中,我需要捕获FileNotFoundException以及随后由close()方法引发的IOException,而在try with resources(在readfile1内部)中,Java没有要求我处理FileNotFoundException,发生了什么 public class TryWithResourcesTest { public static void main(String[] args) { } public st
readFile2()
中,我需要捕获FileNotFoundException
以及随后由close()
方法引发的IOException
,而在try with resources(在readfile1内部)
中,Java没有要求我处理FileNotFoundException
,发生了什么
public class TryWithResourcesTest {
public static void main(String[] args) {
}
public static void readFile1() {
try(Reader reader = new BufferedReader(new FileReader("text.txt"))) {
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readFile2() {
Reader reader = null;
try {
reader = new BufferedReader(new FileReader("text.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if(reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileNotFoundException
是IOException
的子类。抓住后者,你也就抓住了前者。它与try-catch和try-with-resources无关。如果您查看javadocs,就会发现FileNotFoundException是IOException的一个子类