title: Best way to ensure streams that are opened inside a method call get closed
body: <p>I'm calling a method to write some data to a CSV file in java. Inside that method, I'm using a FileWriter that throws an IOException. I'm wondering what the correct way to handle this exception is if I want to handle it in the outer method while also ensuring that the FileWriter gets closed.</p>
  
  <p>I am thinking of two solutions:</p>
  
  <ol>
  <li><p>Just handle the exception inside the method that opens the FileWriter.</p></li>
  <li><p>Figure out a way to pass the FileWriter back to the calling method so that it may be closed.</p></li>
  </ol>
  
  <p>Here's an example of what I'm talking about:</p>
  
  <pre><code>public static void outerFunc() {
      // get some sort of data
      try {
          innerFunc(data);
      }
      catch (IOException e) {
          e.printStackTrace();
      }
      finally {
          // can I close the FileWriter here somehow?
      }
  }
  
  private static void innerFunc(Data data) throws IOException {
      FileWriter csv = new FileWriter("result.csv")
  
      // Write the data to the file
  
      csv.flush();
      csv.close();
  }
  </code></pre>
  
  <p>Let me know what you guys think. I'm very open to the fact that I may be completely off base here and should be doing this a different way. Thank you in advance for any input!</p>