The value of an Optional is taken with get() without checking that it is there
What it finds
result.get() on an Optional throws NoSuchElementException when it is empty, which is what an Optional is for: a value that may be missing. Without a check, the code assumes it is always there. orElse, orElseThrow with a message, ifPresent or map handle the missing case.
Reported are get() calls on variables declared as Optional in a method or lambda that never calls isPresent or isEmpty on the same variable.
From the rule's source, unchecked_optional_get.rs.
import java.util.Optional; class Users { String name(Optional<String> found, Optional<String> other) { String a = found.get();tx0 reports: found.get() throws when the Optional is empty if (other.isPresent()) { return other.get(); } return a; }} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/java:unchecked-optional-get" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/java:unchecked-optional-get] reason="..."tx0 explain tx0/java:unchecked-optional-get shows the same in the terminal. Found a false positive? Report it.