PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Python · Theory

finally

← All stacks

Theory

65/268

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.

Exam tip

finally vs with-statement for files.

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.

Short notes

  • DefCleanup always.
  • UseClose resources.
  • Rememberwith often simpler for files.

Questions

1

Explain finally as if you are teaching a junior — definition, then one tiny script.

2

What does the example print, and why?

3

What mistake do freshers make with finally?

Previous← raiseNextBuilt-in exceptions →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.