Bird
Raised Fist0

You want to ensure a file is always closed after reading, even if an error occurs. Which code correctly uses try-except-finally to do this?

hard🚀 Application Q8 of Q15
Python - Advanced Exception Handling
You want to ensure a file is always closed after reading, even if an error occurs. Which code correctly uses try-except-finally to do this?
Afile = open('data.txt') try: data = file.read() except IOError: print('Read error') finally: file.close()
Btry: file = open('data.txt') data = file.read() except IOError: print('Read error') finally: file.close()
Ctry: file = open('data.txt') data = file.read() finally: file.close() except IOError: print('Read error')
Dfile = open('data.txt') try: data = file.read() finally: file.close() except IOError: print('Read error')
Step-by-Step Solution
Solution:
  1. Step 1: Open file before try block

    Opening file outside try ensures file object exists for finally.
  2. Step 2: Use try-except-finally in correct order

    try reads file, except handles errors, finally closes file.
  3. Final Answer:

    Opens file before try and closes in finally. -> Option A
  4. Quick Check:

    Open before try; close in finally [OK]
Quick Trick: Open resource before try; close in finally [OK]
Common Mistakes:
MISTAKES
  • Opening file inside try but closing outside
  • Placing except after finally
  • Not closing file in finally

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes