Avoid resource leaks in case of exception

Change-Id: I25d012b400ce0f467e6dfa03517bfebd9c945a66