Fix resource leaks in exception handling