Enhancement: Little bit better error handling

- Ensure the file is closed properly when an error occurs