Avoid possible memory leaks in case of exceptions

Change-Id: I411f8f800b7c7f23a7e581a36689f52ff99362c0