Avoid possible memory leaks in case of exceptions

Change-Id: I06525aa32bc17464291126ed676809e23e4227b1