Python Practice › Exception Handling Programs › Program 18
Clean-up with a context manager
Write a Python program showing that a with block closes a file even when an error happens inside it.
Output
caught: something failed file closed: True
Approach
- Raise inside the
withand checkf.closedafterwards.
Solution
try: with open("demo.txt", "w") as f: f.write("data") raise RuntimeError("something failed")except RuntimeError as e: print("caught:", e)print("file closed:", f.closed)Output
caught: something failed file closed: True
Learn the concept
New to this topic? Read the lesson, then come back.