gpt4 book ai didi

java - try catch 与 try-with-resources

转载 作者:行者123 更新时间:2023-12-03 22:00:15 29 4
gpt4 key购买 nike

为什么在 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();
}
}
}

}

最佳答案

FileNotFoundExceptionIOException 的子类。通过捕获后者,你也捕获了前者。它与 try-catch 与 try-with-resources 无关。

关于java - try catch 与 try-with-resources,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56572337/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com