Avoid possible memory leaks in case of exceptions

Change-Id: I957c0662c56e7cad3d10c8bcc1d6b22352da688f