Avoid possible memory leaks in case of exceptions

Change-Id: I288c77190a8205ba320bb788a52f3b2ef9d2557f