Avoid possible memory leaks in case of exceptions

Change-Id: I0cb10efaa3ab08d2cf1338963917d89bdab15289