Avoid possible memory leaks in case of exceptions

Change-Id: I9cafee23bbf016024393550166aefdc782b488cb