Delete temporary file during final delete output file during catch

This is in Java 6.

I have seen more than once that people create temporary files, do something, and then rename them to an output file. Everything is wrapped in a try-finally block, where the temporary file is deleted in finallyif something fails between them.

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 advantages can be made, instead of doing something directly with the output file and deleting 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 assumption is that deleting temporary files is finallybeneficial to me when the try block can throw many exceptions. Did I understand correctly? What else?

+3
source share
4 answers

finally , catch , java.lang.Error, , ( , ... Java IO).

+7

, , .

, finally , catch , .

...

try {
    //do something with tempFile

    //operation is complete since we made it this far; transition
    //tempFile into outputFile
    tempFile.renameTo(outputFile);
}
catch (Exception e) {
    //perform error logic
}
finally {
    if (tempFile.exists())
        tempFile.delete()
}
+3

, , , ( , ). , - , catch.

+2

, / API OS, , API . , , API . TEMP , , , , / , , , , ,

0

Source: https://habr.com/ru/post/1783426/


All Articles