Avoid possible memory leaks in case of exceptions

Change-Id: I1988d2766d8bdeb5f8a22a5673dcff9b898dd637