Avoid possible memory leaks in case of exceptions

Change-Id: Id1c7cb886a892bf0ce7be6774be5408afad44432