Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant code example attempts to delete a file but fails to check whether the operation has succeeded.

Code Block
bgColor#FFcccc

public void deleteFile(){

  File someFile = new File("someFileName.txt");
  // do something with someFile
  someFile.delete();

}

...

This compliant solution checks the boolean value returned by the delete() method and handles any resulting errors.

Code Block
bgColor#ccccff

public void deleteFile(){

  File someFile = new File("someFileName.txt");
  // do something with someFile
  if (!someFile.delete()) {
    // handle failure to delete the file
  }

}

...

This noncompliant code example ignores the return value of the String.replace() method, failing to update the original string. The String.replace() method cannot modify the state of the String (because String objects are immutable); rather, it returns a reference to a new String object containing the modified string.

Code Block
bgColor#FFcccc

public class Replace {
  public static void main(String[] args) {
    String original = "insecure";
    original.replace('i', '9');
    System.out.println(original);
  }
}

...

This compliant solution correctly updates the String reference original with the return value from the String.replace() method.

Code Block
bgColor#ccccff

public class Replace {
  public static void main(String[] args) {
    String original = "insecure";
    original = original.replace('i', '9');
    System.out.println(original);
  }
}

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP00-J

medium

probable

medium

P8

L2

Automated Detection

Tool
Version
Checker
Description
Coverity7.5CHECKED_RETURNImplemented

Related Guidelines

...

[API 2006]

method delete()

 

method replace()

[Green 2008]

String.replace

[Pugh 2009]

Misusing putIfAbsent

 

02. Expressions (EXP)      02. Expressions (EXP)      EXP01-J. Never dereference null pointers