Avoid possible memory leaks in case of exceptions

Change-Id: Idf1460e5207e0797390593535f2b2c080609a77b