Java io ugly try-finally block

This is the correct idom (and it works fine):

   InputStream in = null;
   OutputStream out = null;
   try {
       in = new FileInputStream(inputFileName);
       out = new FileOutputStream(outputFileName);
       copy(in, out);
   finally {
       close(in);
       close(out);
   }

  public static void close(Closeable c) {
     if (c == null) return; 
     try {
         c.close();
     } catch (IOException e) {
         //log the exception
     }
  }

The reason this works fine is that the exception thrown before you got to finally will be thrown after your finally code finishes, provided that your finally code doesn’t itself throw an exception or otherwise terminate abnormally.

Edit: As of Java 7 (and Android SDK 19 – KitKat) there is now a Try with resources syntax to make this cleaner. How to deal with that is addressed in this question.

Leave a Comment