finally

KeywordPython 2.0+Beginner

Block that always executes after try/except, used for cleanup

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

python
# finally runs no matter what
try:
    print("Trying...")
    result = 10 / 2
    print(f"Result: {result}")
finally:
    print("This ALWAYS runs")

print()

# finally runs even when exception occurs
try:
    print("Trying...")
    result = 10 / 0
except ZeroDivisionError:
    print("Caught error")
finally:
    print("Cleanup done")

finally always executes, whether the try block succeeds, raises an exception, or returns. Use it for cleanup like closing files or releasing locks.

Try in Playground

Tags

languagesyntaxcoreerror-handlingcleanup

Related Items