为什么在readFile2()
中,我需要捕获FileNotFoundException
方法抛出的IOException
以及后来在close()
Java中抛出的try-with-resources(inside readfile1)
不要求我处理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();
}
}
}
}
答案 0 :(得分:6)
FileNotFoundException
是IOException
的子类。通过捕获后者,您也可以捕获前者。与try-catch和try-with-resources无关。