Avoid possible memory leaks in case of exceptions

Change-Id: Icecc2cce52d7f27c030270639e6b85877e3aa620