Editor

Fix the Bug: Missing Cleanup

Intermediate · Fix the bug · from Python Context Managers: The with Statement and Building Your Own

From the lesson: Python Context Managers: The with Statement and Building Your Own

Imagine walking through an automatic door at a grocery store. You don't have to push it open or remember to close it behind you. The door opens when you approach and closes when you walk through. It just handles itself.

Read the lesson

This context manager is supposed to always print the cleanup message, even when an error occurs inside the block. But the cleanup never runs when there's an error. Fix the @contextmanager function so cleanup always happens.

The expected output should be:

Setup done
Working...
Cleanup done
from contextlib import contextmanager
@contextmanager
def managed_resource():
print('Setup done')
yield
print('Cleanup done')
try:
with managed_resource():
print('Working...')
raise ValueError('oops')
except ValueError:
pass

More Context Manager exercises

All Python exercises · 50 practice problems · Error Handling quiz