Delete temp file during finally vs delete output file during catch
Posted
by
Russell
on Stack Overflow
See other posts from Stack Overflow
or by Russell
Published on 2011-01-04T15:51:26Z
Indexed on
2011/01/04
15:53 UTC
Read the original article
Hit count: 294
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?
© Stack Overflow or respective owner