Keywords and Control Flow

finally — Cleanup on scope exit

Run cleanup when control leaves an entered try statement, whether normally, through a return or loop transfer, or because an exception propagates. A pending return value is determined before cleanup unless cleanup changes the outcome. If cleanup raises another exception, it can replace the pending exception while retaining the earlier exception as context. In Python 3.13, a return or an exiting loop transfer in finally can discard an outstanding exception; avoid such control flow. Cleanup is not guaranteed after abrupt process termination.

Formal Syntax & Structure

python syntaxpython
try:    suitefinally:    cleanup_suite

Working Example

Example Snippetpython
events = []def calculate():    try:        events.append("work")        return 12    finally:        events.append("cleanup")
print(calculate())print(events)
Python Reference