350-901 · Question #13
open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file)
The correct answer is A. try: open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file) except: print("file not there"). Proper Python exception handling wraps all file operations in the try block so that any failure - including file not found - is caught by the except block.
Question
Options
- Atry: open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file) except: print("file not there")
- Btry: print("file not there") except: open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file)
- Ctry: open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file) except: print("file not there") catch: error(read_file)
- Dopen_file = open("text_file.txt", "r") read_file = open_file.read() try: print(read_file) except: print("file not there")
How the community answered
(19 responses)- A79% (15)
- B5% (1)
- C5% (1)
- D11% (2)
Why each option
Proper Python exception handling wraps all file operations in the try block so that any failure - including file not found - is caught by the except block.
Placing all three file operations (open, read, print) inside the try block ensures that any exception raised at any step - such as FileNotFoundError if the file does not exist - is caught by the except clause, which then prints a user-friendly error message. This is the correct pattern for handling file I/O errors in Python.
The try block only contains the print statement, so the open and read calls outside it would raise an unhandled exception before execution ever reaches the try.
Python does not have a catch keyword; the language uses except for exception handling, making this code a syntax error.
The open call is outside the try block, so a FileNotFoundError during open would be unhandled even though print is wrapped.
Concept tested: Python try/except error handling for file I/O
Source: https://docs.python.org/3/tutorial/errors.html
Topics
Community Discussion
No community discussion yet for this question.