Avoid possible memory leaks in case of exceptions

Change-Id: I9d8d7aabc111d3700fc121277c49eb0f48dc7e44