Avoid possible memory leaks in case of exceptions

Change-Id: Icc073be041ae0b0c690e869a0edaff3515d1d601