尝试捕获与尝试资源

时间:2019-06-13 01:47:38

标签: java exception

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

}

1 个答案:

答案 0 :(得分:6)

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