Avoid possible memory leaks in case of exceptions

Change-Id: Iac63a5d60478e5cd8e2b77c889c7b312d3d15f67