Avoid possible memory leaks in case of exceptions

Change-Id: I22d22a924d33b91ba6894857ce56b0d920102b4b