The except line lacks a colon at the end, which is required in Python.
Step 2: Confirm other parts are correct
try keyword and exception type are correct; only colon is missing.
Final Answer:
Missing colon after except statement -> Option C
Quick Check:
except line must end with colon [OK]
Hint: Always put colon after except statement [OK]
Common Mistakes:
Forgetting colon after except
Assuming wrong exception type causes syntax error
Thinking try keyword is missing
5. You want to open a file and read its content, but the file might not exist. Which code correctly handles this exception?
hard
A. try:
with open('data.txt') as f:
print(f.read())
except:
pass
B. try:
with open('data.txt') as f:
print(f.read())
except FileNotFoundError:
print('File not found')
C. try:
with open('data.txt') as f:
print(f.read())
except ZeroDivisionError:
print('File not found')
D. with open('data.txt') as f:
print(f.read())
except FileNotFoundError:
print('File not found')
Solution
Step 1: Understand the problem
Opening a file that may not exist can cause FileNotFoundError.
Step 2: Check which option correctly catches FileNotFoundError
try:
with open('data.txt') as f:
print(f.read())
except FileNotFoundError:
print('File not found') uses try-except with FileNotFoundError and prints a message, which is correct.
Final Answer:
try:\n with open('data.txt') as f:\n print(f.read())\nexcept FileNotFoundError:\n print('File not found') -> Option B
Quick Check:
Catch FileNotFoundError to handle missing files [OK]
Hint: Catch FileNotFoundError to handle missing files [OK]