When the return value of a function call contain the operation status code, this value should be tested to make sure the operation completed
successfully.
This rule raises an issue when the return values of the following are ignored:
-
java.io.File
operations that return a status code (except mkdirs
)
-
Iterator.hasNext()
-
Enumeration.hasMoreElements()
-
Lock.tryLock()
- non-void
Condition.await*
methods
-
CountDownLatch.await(long, TimeUnit)
-
Semaphore.tryAcquire
-
BlockingQueue
: offer
, remove
, drainTo
,
Noncompliant Code Example
public void doSomething(File file, Lock lock) {
file.delete(); // Noncompliant
// ...
lock.tryLock(); // Noncompliant
}
Compliant Solution
public void doSomething(File file, Lock lock) {
if (!lock.tryLock()) {
// lock failed; take appropriate action
}
if (!file.delete()) {
// file delete failed; take appropriate action
}
}
See
- MISRA C:2004, 16.10 - If a function returns error information, then that error information shall be tested
- MISRA C++:2008, 0-1-7 - The value returned by a function having a non-void return type that is not an overloaded operator shall always be used.
- MISRA C:2012, Dir. 4.7 - If a function returns error information, then that error information shall be tested
- MISRA C:2012, 17.7 - The value returned by a function having non-void return type shall be used
- CERT, ERR33-C. - Detect and handle standard library errors
- CERT, POS54-C. - Detect and handle POSIX library errors
- CERT, EXP00-J. - Do not ignore values returned by methods
- CERT, EXP12-C. - Do not ignore values returned by functions
- CERT, EXP12-CPP. - Do not ignore values returned by functions or methods
- CERT, FIO02-J. - Detect and handle file-related errors
- MITRE, CWE-754 - Improper Check for Unusual Exceptional Conditions