Avoid possible memory leaks in case of exceptions

Change-Id: I32d1e15cb9f050e3cd05babbd2f21c57f3ccb5e7