Avoid possible memory leaks in case of exceptions

Change-Id: I5e302cf7ac784e1413c0539d0c967a3523f04ba0