Avoid possible memory leaks in case of exceptions

Change-Id: Ia2925804755220b8bd160da8997b1bf3161aa27b