Avoid possible memory leaks in case of exceptions

Change-Id: If541e39e34490adccc8baab43ea9516c3dc6cc1a