Avoid possible memory leaks in case of exceptions

Change-Id: Id24acc128cf345a660e552f64c857906229f59c0