Avoid possible memory leaks in case of exceptions

Change-Id: I43cce6b6c41582a65ff7e59de9a107b30cf8b1e8