Clean-up with a context manager

EasyException Handling Programs · 18 of 20

Write a Python program showing that a with block closes a file even when an error happens inside it.

Advertisement
Output
caught: something failed
file closed: True

Approach

  1. Raise inside the with and check f.closed afterwards.

Solution

Python
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.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment