The analyzer has detected an addressing to the object Optional, which, in turn, is potentially empty. In such a case, there the 'NoSuchElementException' exception will be generated.
Let's consider an example:
PClient getClient(boolean cond, String name, String company, /*args*/)
{
Optional<PClient> optClient = cond ?
Optional.of(new PClient(name, company)) : Optional.empty();
...
PClient pClient = optClient.get();
...
return pClient;
}
After executing the first string, the 'optClient' object can be initialized by an empty Optional depending on the condition. In such a case, a string 'optClient.get()' will generate an exception for which there is no check. This could happen because of carelessness or after refactoring. As an option, code can be corrected as follows:
PClient getClient(boolean cond, String name, String company, /*args*/)
{
Optional<PClient> optClient = cond ?
Optional.of(new PClient(name, company)) : Optional.empty();
...
if (optClient.isPresent())
{
PClient pClient = optClient.get();
...
return pClient;
}
else
{
return null;
}
}
This diagnostic is classified as:
You can look at examples of errors detected by the V6036 diagnostic. |