V6036. The value from the uninitialized optional is used.

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.


Bugs Found

Checked Projects
411
Collected Errors
14 123
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →
Accept