try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
} catch (FileNotFoundException fnf) {
fnf.printStackTrace();
} finally {
fr.close();
}
The fr.close() shows an error:
fr cannot be resolved
I had read that closing a file in the finally block is a good practice.
What is that am doing wrong?
The variable
fronly has scope within thetryblock. It is out of scope in the finally block. You need to declare it before thetryblock:This is quite a common pattern of code, so it’s good to remember it for future similar situations.
Consider throwing
IOExceptionfrom this method – printing track traces isn’t very helpful to callers, and you wouldn’t need the nested try catch aroundfr.close()