Bird
Raised Fist0

Identify the problem in this code snippet:

medium📝 Debug Q7 of Q15
Python - Exception Handling Fundamentals
Identify the problem in this code snippet:
try:
    file = open('data.txt')
except FileNotFoundError:
    print('File missing')
finally:
    file.close()
Afile may not be defined if exception occurs
BFileNotFoundError is not a valid exception
Cfinally block cannot be used with try-except
Dfile.close() should be inside except block
Step-by-Step Solution
Solution:
  1. Step 1: Understand variable scope in try-except-finally

    If opening the file fails, 'file' is not assigned, so calling file.close() causes an error.
  2. Step 2: Identify the error cause

    The finally block runs always, but 'file' may be undefined if exception occurs, causing a NameError.
  3. Final Answer:

    file may not be defined if exception occurs -> Option A
  4. Quick Check:

    Undefined variable in finally causes error [OK]
Quick Trick: Check variable defined before using in finally [OK]
Common Mistakes:
MISTAKES
  • Assuming finally block can't be used
  • Thinking FileNotFoundError is invalid
  • Placing close() only in except block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes