A small web application allows users to download files from a server. The code uses open() without any exception handling. When a user requests a non-existent file, the server crashes with a traceback and returns a 500 Internal Server Error to the client. The team needs to modify the code to handle this situation gracefully: if the file does not exist, the application should return a 404 Not Found response (by calling a function send_404()). The application should not catch unrelated exceptions like KeyboardInterrupt. Which modification is the most appropriate?
Specifically handles the missing file case without catching unrelated errors.
Why this answer
Option D is correct because it catches the specific exception raised when a file is not found (FileNotFoundError), which is a subclass of OSError. This allows the code to return a 404 response for missing files while not catching unrelated exceptions like KeyboardInterrupt, as required. The except block calls send_404() to handle the missing file gracefully without crashing the server.
Exam trap
Python Institute often tests the distinction between catching a specific exception (FileNotFoundError) versus its parent class (OSError), and the trap here is that candidates may choose the broader OSError (Option C) thinking it covers all file-related errors, but that would incorrectly handle permission or other OS errors as 404s.
How to eliminate wrong answers
Option A is wrong because it catches all exceptions (including KeyboardInterrupt) and calls send_500(), which does not distinguish between a missing file and other errors, violating the requirement to not catch unrelated exceptions. Option B is wrong because it introduces a race condition: between checking os.path.exists and opening the file, the file could be deleted or renamed, leading to an unhandled exception. Option C is wrong because catching OSError is too broad; it would catch other OS-related errors (e.g., permission denied) and incorrectly return a 404, when the requirement is to only handle non-existent files with a 404 response.