为什么在readFile2()中我需要捕获FileNotFoundException,然后是close()方法抛出的IOException,而在try-with-resources(inside 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();
}
}
}
}发布于 2019-06-13 09:49:42
FileNotFoundException是IOException的一个子类。通过捕捉后者,你也可以捕捉到前者。它与try-catch和try- with -resources没有任何关系。
https://stackoverflow.com/questions/56572337
复制相似问题