Avoid possible memory leaks in case of exceptions

Change-Id: Id6590e6c1d3ec1640ebf55d348670953450dd419