How can I get rid of this error?
The problem is that if the BufferedReader
or FileReader
constructor throws an exception, br
will be null but you're still unconditionally calling br.close()
. Check whether br
is null before you close it in the finally block:
finally {
if (br != null) {
br.close();
}
}
Alternatively, assign it before the try
block:
BufferedReader br = new BufferedReader(...);
try {
...
} catch (...) {
...
} finally {
br.close(); // br will definitely not be null
}
Or even better in Java 7, use a try-with-resources statement:
try (BufferedReader br = new BufferedReader(...)) {
...
} catch (...) {
...
}
Note that currently your catch
blocks are dumping the error but then continuing as if nothing's happened - whereas I'd expect the exception to be propagated to the caller. What do you want to happen if the file can't be read? (With the second and third changes I've suggested, you'd still be swallowing exceptions for actual reading, but not on opening the file.)