Avoid possible memory leaks in case of exceptions

Change-Id: I8bdb8ca84b75efde4effba1ce76704d2c7c3f214