Avoid possible memory leaks in case of exceptions

Change-Id: Icff534ac96e0a595d71bc34b6055caf8cd096ad8