Avoid possible memory leaks in case of exceptions

Change-Id: I9a92edd7886db484f1333585545f6f63a233a6dd