Avoid possible memory leaks in case of exceptions

Change-Id: I1a566a870a3bde91a527ac454fc9946e99a2593e