try catch vs try-with-resources

Johnny Pepperoni :

Why in the readFile2() I need to catch the FileNotFoundException and later the IOException that is thrown by the close() method, and in the try-with-resources(inside readfile1) Java doesn't ask me to handle the FileNotFoundException, what happened?

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();
            }
        }
    }

}
Joseph Sible-Reinstate Monica :

FileNotFoundException is a subclass of IOException. By catching the latter, you're catching the former too. It has nothing to do with try-catch vs. try-with-resources.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114424&siteId=1
Recommended