Avoid possible memory leaks in case of exception

Change-Id: Ie8c1a3e54bda4ec650f5d5da3928d3c44e4008a8