java - try catch 与 try-with-resources

标签 java exception

为什么在 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/

相关文章:

java - 为什么删除 SQLite 数据库 JAR 后 java.sql.DriverManager.getConnection() 仍然有效?

java - 如何添加 e.getmessage() 作为 java 方法的返回

c# - 如何模拟 "Throws"和 "ThrowsAsync"中的异常类型

c# - DateTime.ParseExact 方法 : always throws exception even with correct format 的问题

eclipse Java EE IDE 更新后无法启动

Java 分割字符串的连续分隔符

java - 为什么同样宽高的图片尺寸不一样?

java - IBM JRE gencon 策略中的歧义和详细 :gc output

C# Image.Clone 内存不足异常

c++ - 安全地传递指针所有权异常