Avoid possible memory leaks in case of exceptions

Change-Id: Ib74c40bb4ac11edf97b6843e983a911308fa4b98