Missing handling of file deletion result Medium

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.

Detector ID
java/missing-file-deletion-result-check@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

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}

Compliant example

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}