Avoid possible memory leaks in case of exceptions

Change-Id: I0cea121c8a8dbbc7b9f44ab712ff692243889816