Avoid infinite loop upon invalid input and fix ticket #4922.