Avoid possible memory leaks in case of exceptions

Change-Id: I4f1e00dd275976cdba8490f35ccbb491914829b7