title: try...catch inside finally when releasing resource?
body: <p>I want to write a <code>String</code> to a Unicode file. My code in <code>Java</code> is:</p>
  
  <pre><code>public static boolean saveStringToFile(String fileName, String text) {
      BufferedWriter out = null;
      boolean result = true;
      try {
          File f = new File(fileName);
          out = new BufferedWriter(new OutputStreamWriter(
                  new FileOutputStream(f), "UTF-8"));
          out.write(text);
          out.flush();
      } catch (Exception ex) {
          result = false;
      } finally {
          if (out != null)
              try {
                  out.close();
              } catch (IOException e) {
                  // nothing to do! couldn't close
              }
      }
  
      return result;
  }
  </code></pre>
  
  <h3>Update</h3>
  
  <p>Now compare it to C#:</p>
  
  <pre><code>    private static bool SaveStringToFile(string fileName, string text)
      {
          using (StreamWriter writer = new StreamWriter(fileName))
          {
              writer.Write(text);
          }
      }
  </code></pre>
  
  <p>or even <code>try..catch</code> form would be:</p>
  
  <pre><code>    private static bool SaveStringToFile(string fileName, string text)
      {
          StreamWriter writer = new StreamWriter(fileName);
          try
          {
              writer.Write(text);
          }catch (Exception ex)
          {
              return false;
          }
          finally
          {
              if (writer != null)
                  writer.Dispose();
          }
      }
  </code></pre>
  
  <p>Maybe it's because I'm from the C# and .Net world. But is this the right way to write a String to a file? It's just too much code for such simple task. In C#, I would say to just <code>out.close();</code> and that was it but it seems a bit strange to add a <code>try..catch</code> inside a <code>finally</code> statement. I added the <code>finally</code> statement to close the file (resource) no matter what happens. To avoid using too much resource. Is this the right way in Java? If so, why <code>close</code> throws exception?</p>