Avoid possible memory leaks in case of exceptions

Change-Id: Icc1e11e173329fd88898a3d13270406fd651eb2b