title: Java try/catch/finally best practices while acquiring/closing resources
body: <p>While working on a school project, I wrote the following code:</p>
  
  <pre><code>FileOutputStream fos;
  ObjectOutputStream oos;
  try {
      fos = new FileOutputStream(file);
      oos = new ObjectOutputStream(fos);
  
      oos.writeObject(shapes);
  } catch (FileNotFoundException ex) {
      // complain to user
  } catch (IOException ex) {
      // notify user
  } finally {
      if (oos != null) oos.close();
      if (fos != null) fos.close();
  }
  </code></pre>
  
  <p>The problem is that Netbeans is telling me the <code>resource.close()</code> lines throw an <code>IOException</code> and therefore must either be caught or declared. It also is complaining that <code>oos</code> and <code>fos</code> might not yet be initialized (despite the null checks).</p>
  
  <p>This seems a little strange, seeing as how the whole point is to stop the <code>IOException</code> right there.</p>
  
  <p>My knee-jerk fix is to do this:</p>
  
  <pre><code>} finally {
      try {
          if (oos != null) oos.close();
          if (fos != null) fos.close();
      } catch (IOException ex) { }
  }
  </code></pre>
  
  <p>But deep down this bothers me and feels dirty.</p>
  
  <p>I come from a C# background, where I would simply take advantage of a <code>using</code> block, so I am unsure of what the "right" way is to handle this.</p>
  
  <p>What <em>is</em> the right way to handle this problem?</p>