Avoid possible memory leaks in case of exceptions

Change-Id: I1dd003bc984a11d6d71c92aae44accc9d358db0c