Select your cookie preferences

We use essential cookies and similar tools that are necessary to provide our site and services. We use performance cookies to collect anonymous statistics, so we can understand how customers use our site and make improvements. Essential cookies cannot be deactivated, but you can choose “Customize” or “Decline” to decline performance cookies.

If you agree, AWS and approved third parties will also use cookies to provide useful site features, remember your preferences, and display relevant content, including relevant advertising. To accept or decline all non-essential cookies, choose “Accept” or “Decline.” To make more detailed choices, choose “Customize.”

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}