...
This noncompliant code example attempts to delete a file but fails to check whether the operation has succeeded.:
Code Block | ||
---|---|---|
| ||
public void deleteFile(){ File someFile = new File("someFileName.txt"); // doDo something with someFile someFile.delete(); } |
...
This compliant solution checks the boolean
Boolean value returned by the delete()
method and handles any resulting errors.:
Code Block | ||
---|---|---|
| ||
public void deleteFile(){ File someFile = new File("someFileName.txt"); // doDo something with someFile if (!someFile.delete()) { // handleHandle failure to delete the file } } |
...
It is especially important to process the return values of immutable object methods. While Although many methods of mutable objects operate by changing some internal state of the object, methods of immutable objects cannot change the object and often return a mutated new object, leaving the original object unchanged.
...
This compliant solution correctly updates the String
reference original
with the return value from the String.replace()
method.:
Code Block | ||
---|---|---|
| ||
public class Replace { public static void main(String[] args) { String original = "insecure"; original = original.replace('i', '9'); System.out.println(original); } } |
...
Ignoring method return values can lead to unexpected program behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP00-J |
Medium |
Probable |
Medium | P8 | L2 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar |
| JAVA.NULL.RET.UNCHECKED | Call Might Return Null (Java) | ||||||
Coverity | 7.5 | CHECKED_RETURN | Implemented | ||||||
Parasoft Jtest |
| CERT.EXP00.NASSIG CERT.EXP00.AECB | Ensure method and constructor return values are used Avoid "try", "catch" and "finally" blocks with empty bodies | ||||||
PVS-Studio |
| V6010, V6101 | |||||||
SonarQube |
| Return values from functions without side effects should not be ignored Return values should not be ignored when they contain the operation status code | |||||||
SpotBugs |
| RV_RETURN_VALUE_IGNORED | Implemented |
Related Guidelines
VOID EXP12-CPP. Do not ignore values returned by functions or methods | |
Passing Parameters and Return Values [CSJ] | |
, Unchecked |
Return Value |
Bibliography
...
02. Expressions (EXP) 02. Expressions (EXP) EXP01-J. Never dereference null pointers