Avoid possible memory leaks in case of exceptions

Change-Id: If1057871aa7c9e7079ed051e6854c77c81f12292