I found this example in the try-with-resources documentation for Java:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
If the constructor for BufferedReader
throws an exception, then the resources held by the FileReader
won't be released. So isn't this a bad practice to write it like that instead of:
static String readFirstLineFromFile(String path) throws IOException {
try (FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr)) {
return br.readLine();
}
}