Avoid possible memory leaks in case of exceptions

Change-Id: I7dc862794f7f0973bd4de7b54f7a1fb15235bc3e