尝试捕获与尝试资源

Joh*_*oni 2 java exception

在为什么readFile2()我需要赶上FileNotFoundException,后来IOException由抛出的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();
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ica 6

FileNotFoundException是的子类IOException。通过捕获后者,您也可以捕获前者。它与try-catch与try-with-resources无关。