Avoid possible memory leaks in case of exceptions

Change-Id: I1d703da6c0f9fd1a7e2423cc609fb504bb553382