Avoid possible memory leaks in case of exceptions

Change-Id: Idbb2318a51ba9f39c20deb036975a8e85e8d231f