Avoid possible memory leaks in case of exceptions

Change-Id: Idb8f0df3848416d96299ebc47ac5bd53d766e52c