Avoid possible memory leaks in case of exceptions

Change-Id: Id71cb49d8aa241a17efd4cbe217a48f2d7c34e84