Avoid possible memory leaks in case of exceptions

Change-Id: Ic9b9c22c0ad15bfefce729e7277f950cb66d9bf6