Avoid possible memory leaks in case of exceptions

Change-Id: I047fd88a89900153089a55b6af123f11fb8bde55