Avoid possible memory leaks in case of exceptions

Change-Id: Ibadadacbe09a93e7d7a7210868c52a8fa582d427