Avoid possible memory leaks in case of exceptions

Change-Id: I4b2b439615db0ff4598f405d1e339eebbff7ae91