avoid InvalidOperation and NullReferenceException

fixes #5522