Avoid possible memory leaks in case of exceptions

Change-Id: I95a769fe436a79a1e236c5504d1d5b288b3da71a