Avoid possible memory leaks in case of exceptions

Change-Id: Ib4a87cab2729e18b2c830cbd7e7a34d62b5f0f45