Delete temp file during finally vs delete output file during catch
- by Russell
This is in Java 6.
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 finally in case something goes wrong in between.
try {
//do something with tempFile
//do something with tempFile
//do something with tempFile
tempFile.renameTo(outputFile);
}
finally {
if (tempFile.exists())
tempFile.delete()
}
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.
try {
//do something with outputFile
//do something with outputFile
//do something with outputFile
}
catch (Exception e) {
if (outputFile.exists())
outputFile.delete();
}
My guess is that deleting temp files in finally benefits me when the try block can throw many kinds of exceptions. Is my guess right? What else?