Avoid possible memory leaks in case of exceptions

Change-Id: Id75c459cfa59fe2adfc0f748dc33d0bc9e271507