Bird
Raised Fist0

Consider this code:

hard🚀 Application Q9 of Q15
Python - Context Managers
Consider this code:
class Logger:
    def __enter__(self):
        print('Log start')
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            print(f'Error: {exc_val}')
        print('Log end')

with Logger() as log:
    print('Running')
    1 / 0

What will be printed before the program stops?
ALog start Error: division by zero Running Log end
BLog start Running Error: division by zero Log end
CRunning Log start Error: division by zero Log end
DLog start Running Log end
Step-by-Step Solution
Solution:
  1. Step 1: Trace normal and exception flow

    __enter__ prints 'Log start'. Inside block, 'Running' prints, then division by zero raises exception.
  2. Step 2: __exit__ handles exception

    __exit__ detects exception, prints error message, then prints 'Log end'.
  3. Final Answer:

    Log start Running Error: division by zero Log end -> Option B
  4. Quick Check:

    __exit__ runs even on exceptions [OK]
Quick Trick: __exit__ runs on exceptions and can handle them [OK]
Common Mistakes:
MISTAKES
  • Assuming __exit__ does not run on error
  • Mixing print order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes