Avoid possible memory leaks in case of exceptions

Change-Id: Iad3de981a1c9660b1322315640e531c9891db0bf