V6073. It is not recommended to return null or throw exceptions from 'toString' / 'clone' methods.


The analyzer has detected an overridden 'toString' or 'clone' method that can return a 'null' value or throw an exception.

The 'toString' / 'clone' method must always return a string / object respectively. Returning an invalid value contradicts the method's implicit contract.

The following example demonstrates incorrect overriding of the 'toString' method:

@Override
public String toString()
{
  return null;
}

The developer who would be using or maintaining the program in the future is likely to call this method to get the textual representation of the object. Since they are unlikely to check the return result for null, using it may lead to throwing a 'NullPointerException'. If you want the method to return an empty or unknown value as the object's textual representation, it is recommended to use an empty string:

@Override
public String toString()
{
  return "";
}

Throwing an exception is another bad practice when implementing the 'toString' method. This is demonstrated by the following synthetic example:

@Override
public String toString()
{
  if(hasError)
  {
    throw new IllegalStateException("toString() method error encountered");
  }
  ....
}

The user of the class is very likely to call this method at a point where no exception throwing and handling is provided for.

If you want an error message to appear when generating an object's textual representation, either return the message text as a string or log the error:

....
@Override
public String toString()
{
  if(hasError)
  {
    logger.warn("toString() method error encountered");
    return "Error encountered";
  }
  ....
}

All said above holds true for the 'clone' method. When calling it, you count only on one of the two possible outcomes:

  • if the copy operation is not supported for this instance, you expect a 'CloneNotSupportedExcexption';
  • if copying is possible, the method is guaranteed to create and return a correct copy of the object.

But you never expect either of the following options:

  • throwing an unexpected exception;
  • getting null instead of the correct copy.

Bugs Found

Checked Projects
364
Collected Errors
13 504