Avoid possible memory leaks in case of exceptions

Change-Id: I55f418ebcb96b44ab423a676881ffe8f455a923d