Problem Statement
Explain reliable resource cleanup with finally and how it compares to using a context manager.
Explanation
finally runs no matter what, including when exceptions occur or returns happen. This makes it a reliable place to close files, release locks, or restore state. It protects cleanup from early exits and errors.
A context manager packages this pattern in a reusable form. The enter step acquires a resource, and the exit step guarantees release. Prefer with for common patterns and use finally when you need custom control flow in one place.
Code Solution
SolutionRead Only
f=None
try:
f=open('data.txt','r',encoding='utf-8')
use(f)
finally:
if f: f.close()