Avoid possible resource leaks in case of exceptions

Change-Id: I6f1f6669b222f03ad220f01cae2e09d03550a58b