added a line to close the file when an exception has been caught