All,
I am trying to ensure that a file I have open with BufferedReader is closed when I catch an IOException, but it appears as if my BufferedReader object is out o
My preferred way of performing clean-up after an exception (when the clean-up can potentially also throw an exception) is to put the code in the try block inside another try/finally block, as follows:
public static ArrayList readFiletoArrayList(String fileName, ArrayList fileArrayList) {
fileArrayList.removeAll(fileArrayList);
try {
//open the file for reading
BufferedReader fileIn = null;
try {
fileIn = new BufferedReader(new FileReader(fileName));
// add line by line to array list, until end of file is reached
// when buffered reader returns null (todo).
while(true){
fileArrayList.add(fileIn.readLine());
}
} finally {
if (fileIn != null) {
fileIn.close();
}
}
}catch(IOException e){
fileArrayList.removeAll(fileArrayList);
return fileArrayList; //returned empty. Dealt with in calling code.
}
}