Reputation: 65
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();
}
}
}
}
Upvotes: 2
Views: 72
Reputation: 48572
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.
Upvotes: 6