Avoid possible memory leaks in case of exceptions

Change-Id: I185e957da57f4da7dbd2b95496bcd5349fc7d039