Updated stream closing logic to close stream in the finally close