Java and IOException handling

What’s wrong with this Java snippet?

  static String readFirstLineFromFile(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
}

The answer: if an IOException occurs, the FileReader is not closed. The calling method that catches the exception can report the exception but doesn’t have the opportunity to handle the exception.

Here’s an improved (although not perfect) version:

  static String readFirstLineFromFile(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
br.close();
}
}

This is a “you can only find it through careful code review” bug.

Our C# colleagues have a language feature designed for these situations. Joshua “Effective Java” Bloch proposes such a feature for Java 7, called “Automatic Resource Management”.

Why do I mention this? In keeping up with what’s coming for Java 7, I stumbled upon this proposal. I realised that in Poker Copilot’s Java code, I frequently use the poor idiom at the top of this blog entry. But I stand in good company: According to Joshua, 2/3 of the uses of the close method in the JDK are wrong.