Avoid possible memory leaks in case of exceptions

Change-Id: I27a0c3639c346720df471ffa3940783565c47f7d