finally — Python Technical Interview Questions & Answers
finally
finally
- finally runs cleanup whether an error happened or not. Close a file, release a lock, reset a flag. try: risky. except: handle. finally: cleanup. For files, with open(...) as f: often replaces manual finally. still learn finally for custom cleanup.
- Almost always runs (rare interpreter-exit edges). Viva: finally vs with — with is nicer for files; finally is the general cleanup keyword.
- Output: Cannot divide then finally always. finally still runs after except.
Technical Interview Tip: finally vs with-statement for files.
Code Examples for finally
Example
# finally
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide")
finally:
print("finally always")
Output: Cannot divide then finally always. finally still runs after except.
How to Explain finally to an Interviewer
Explain finally as if you are teaching a junior — definition, then one tiny script.
Cleanup always. Close resources.
What does the example print, and why?
Cannot divide then finally always
What mistake do freshers make with finally?
with often simpler for files.