Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q13 of 15
Python - Context Managers
What will be the output of this code?
try:
    with open('test.txt', 'w') as f:
        f.write('Hello')
        raise Exception('Error')
except Exception:
    print('Caught error')
print(f.closed)
ACaught error\nFalse
BTrue\nCaught error
CFalse\nCaught error
DCaught error\nTrue
Step-by-Step Solution
Solution:
  1. Step 1: Understand 'with' and exceptions

    The 'with' block ensures the file is closed even if an exception occurs inside it.
  2. Step 2: Trace code execution

    Exception is raised inside 'with', caught by except, prints 'Caught error'. Then print(f.closed) shows True because file is closed.
  3. Final Answer:

    Caught error\nTrue -> Option D
  4. Quick Check:

    Context manager closes file despite error = True [OK]
Quick Trick: Files close automatically even if errors happen inside 'with' [OK]
Common Mistakes:
  • Assuming file stays open after exception
  • Confusing order of print outputs
  • Ignoring exception handling

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes