Avoid possible memory leaks in case of exceptions

Change-Id: I8914e0dc253c636a1393672f7a20bcb5d39d4276