Avoid possible memory leaks in case of exceptions

Change-Id: I9983e858c4e634b4cac8ad42fa9b06b7ccc167d6