Avoid possible memory leaks in case of exceptions

Change-Id: I9783669a26fd9c9e2c890f430b29427ccf6bea77