The result of deleting files should be checked and failure should be logged. For example, java.io.File.delete()
simply returns false
if it fails to delete the file when it does not exist. It will not throw an exception unless there is a security exception.
1public void fileDeletionNoncompliant(File file) {
2 if (file.exists()) {
3 log.info("Deleting file: " + file.getName());
4 // Noncompliant: result of file deletion not checked.
5 file.delete();
6 }
7}
1public void fileDeletionCompliant(File file) {
2 if (file.exists()) {
3 log.info("Deleting file: " + file.getName());
4 // Compliant: result of file deletion is checked.
5 if (!file.delete()) {
6 throw new RuntimeException("Failed to delete the file!");
7 }
8 }
9}