为什么在 readFile2()
中我需要捕获 FileNotFoundException
以及稍后由 close( )
方法,并且在 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();
}
}
}
}
最佳答案
FileNotFoundException
是 IOException
的子类。通过捕获后者,你也捕获了前者。它与 try-catch 与 try-with-resources 无关。
关于java - try catch 与 try-with-resources,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56572337/