How do I close a file after catching an IOException in java?

后端 未结 7 1295
独厮守ぢ
独厮守ぢ 2021-01-05 08:07

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

7条回答
  •  天命终不由人
    2021-01-05 08:27

     BufferedReader fileIn = null;
     try {
           fileIn = new BufferedReader(new FileReader(filename));
           //etc.
     } catch(IOException e) {
          fileArrayList.removeall(fileArrayList);
     } finally {
         try {
           if (fileIn != null) fileIn.close();
         } catch (IOException io) {
            //log exception here
         }
     }
     return fileArrayList;
    

    A few things about the above code:

    • close should be in a finally, otherwise it won't get closed when the code completes normally, or if some other exception is thrown besides IOException.
    • Typically you have a static utility method to close a resource like that so that it checks for null and catches any exceptions (which you never want to do anything about other than log in this context).
    • The return belongs after the try so that both the main-line code and the exception catching have a return method without redundancy.
    • If you put the return inside the finally, it would generate a compiler warning.

提交回复
热议问题