Avoid possible memory leaks in case of exceptions

Change-Id: Ifd4c87bf038b421a0468edb599eca030c78bad89