Avoid possible memory leaks in case of exceptions

Change-Id: I4c9d1746d43642e1be2dd1e72a1b689d3fae1ae6