Avoid possible memory leaks in case of exceptions

Change-Id: I03096fe1da8a111312f9384b94cfcb2ead7b3d38