Release resources
A file, socket, lock, or other external resource must be released after an operation regardless of success or failure.
Python · Const
Python’s finally clause runs cleanup code after a try statement, regardless of whether an exception occurs. It also runs before return, break, or continue leaves the try statement.
A finally clause is attached to a try statement to run cleanup code after the try block and any applicable except or else clauses. If an exception remains unhandled, it is re-raised after cleanup; control-flow statements in finally can override that behavior.
try:
suite
finally:
suitefinally for cleanup actions that must run after a try operation.finally follows the complete try statement, including its optional except and else parts.return, break, or continue still triggers the cleanup suite first.return, break, or continue in finally: these statements discard an exception that would otherwise be re-raised.return in finally overrides an earlier return value, so it can silently replace the result from the try block.def read_config(path):
file = open(path, encoding="utf-8")
try:
return file.read()
finally:
file.close()
print(read_config("config.txt"))The file is closed whether reading succeeds or raises an exception.
A file, socket, lock, or other external resource must be released after an operation regardless of success or failure.
Temporary state or bookkeeping must be restored after a protected operation.
An operation may exit early through a return or loop-control statement but still needs mandatory finalization.
finally clause run?finally is a cleanup handler. It runs after the try suite, including any except and else suites, whether or not an exception occurred.
Follow-up: What happens to an unhandled exception? It is temporarily saved, cleanup runs, and the exception is re-raised after the finally suite unless control flow in finally overrides it.
finally interact with exceptions?An unhandled exception from the try, except, or else clauses is saved while finally executes. If finally completes normally, that exception is re-raised afterward.
Follow-up: What if finally raises a new exception? The saved exception becomes the context of the new exception.
try statement?A return, break, or continue in the try suite still causes finally to execute before control leaves. The function's return value is determined by the last return statement executed.
Follow-up: Why is return in finally risky? Because finally always executes, its return is last and can suppress an exception or replace an earlier result.
try statementexcept clauseelse clausereturn statementbreak statementcontinue statementwith statement