Avoid possible memory leaks in case of exceptions

Change-Id: Id8a85f6c7bcf8eed4688ebebf30b1b74676dae0d