title: Delete temp file during finally vs delete output file during catch
body: <p>This is in Java 6.</p>
  
  <p>I've seen more than once that people create temp files, do something, then rename it to the output file. Everything is wrapped in a try-finally block, where the temp file is deleted in <code>finally</code> in case something goes wrong in between.</p>
  
  <pre><code>try {
      //do something with tempFile
      //do something with tempFile
      //do something with tempFile
      tempFile.renameTo(outputFile);
  }
  finally {
      if (tempFile.exists())
          tempFile.delete()
  }
  </code></pre>
  
  <p>I was wondering what are the benefits of doing that instead of doing something to the output file directly and delete it in case of exceptions.</p>
  
  <pre><code>try {
      //do something with outputFile
      //do something with outputFile
      //do something with outputFile
  }
  catch (Exception e) {
      if (outputFile.exists())
          outputFile.delete();
  }
  </code></pre>
  
  <p>My guess is that deleting temp files in <code>finally</code> benefits me when the try block can throw many kinds of exceptions. Is my guess right? What else?</p>