Sub topic 7
Guaranteed cleanup with finally
This chapter assumes you can write try and except blocks, know that exceptions travel up the call stack, and can read a basic traceback. The finally clause runs a block of code whether the try body succeeds, raises, or leaves the function early. You use it to release resources such as files, locks, connections, and temporary state.
What finally guarantees
A finally block runs after the try block and any except or else clause has finished. It runs on every normal way out of the statement:
- The
trybody finishes without an error. - The
trybody raises an exception that anexceptclause handles. - The
trybody raises an exception that no clause handles. - Control leaves through
return,break, orcontinue. - An
exceptorelseblock raises a new exception.
The next example prints one line at each stage, so you can see the order.
def demo(value):
print("start")
try:
result = 10 / value
except ZeroDivisionError:
print("except")
return "error"
else:
print("else")
return result
finally:
print("finally")
print(demo(2))
print(demo(0))Calling demo(2) prints start, else, finally, and then 5.0. Calling demo(0) prints start, except, finally, and then error. In both calls the return statement computes its value first. Python then runs finally, and only afterwards does the function hand the value to its caller.
try/finally without except
You do not need an except clause to use finally. A try/finally statement does not handle the error. It only promises that cleanup happens while the error continues upward.
def read_first_line(path):
f = open(path)
try:
return f.readline()
finally:
f.close()
print("file closed")If readline() raises, for example a UnicodeDecodeError from a file with bad bytes, the file is closed. The exception then continues to the caller with its original traceback. The function does not decide how to recover. It only makes sure it does not leak the file handle.
Where to acquire the resource
Acquire the resource before the try statement, not inside it. The next version looks similar but has a bug.
def broken(path):
try:
f = open(path)
return f.readline()
finally:
f.close()
broken("missing.txt")If open() fails, f was never assigned. The finally block then raises UnboundLocalError. That error hides the real FileNotFoundError, which is the one you needed to see. Python still shows the original error in the traceback as context, but the exception your callers receive is the wrong one.
The rule is to put only the code that needs the cleanup inside the try. If acquiring the resource fails, there is nothing to clean up, so no finally should run.
Several resources and cleanup order
When you hold more than one resource, nest the statements. Each resource then has its own try/finally.
def copy_first_line(src, dst):
inp = open(src)
try:
out = open(dst, "w")
try:
out.write(inp.readline())
finally:
out.close()
finally:
inp.close()Cleanup runs in reverse order of acquisition, so out closes before inp. This order matters when a later resource depends on an earlier one, such as a cursor that depends on a connection. If open(dst, "w") fails, inp still gets closed.
Deep nesting like this is hard to read. That is the reason context managers exist, and they appear later in this chapter.
What happens when finally itself raises
Cleanup code can fail too. If a finally block raises while another exception is pending, the new exception replaces the old one. Python keeps the old one in the new exception's __context__ attribute.
def cleanup_fails():
try:
raise ValueError("original")
finally:
raise RuntimeError("cleanup failed")
try:
cleanup_fails()
except RuntimeError as exc:
print(repr(exc))
print(repr(exc.__context__))This prints RuntimeError('cleanup failed') and then ValueError('original'). The traceback also shows both errors, joined by the line "During handling of the above exception, another exception occurred".
Two habits reduce the risk:
- Keep
finallyblocks short and simple, so they have little that can fail. - If cleanup can fail and the main error is more important, wrap the cleanup in its own
try/exceptand log the cleanup error.
import logging
logger = logging.getLogger(__name__)
def run(resource):
try:
resource.use()
finally:
try:
resource.close()
except Exception:
logger.exception("close failed")Here a failed close() is logged, and any exception from use() still reaches the caller.
Which exits run finally
finally runs for exceptions that except Exception would not catch, because it does not look at the exception type at all. It runs for KeyboardInterrupt when the user presses Ctrl+C. It also runs for SystemExit, which sys.exit() raises. For this reason finally is the right tool for cleanup, and a broad except is not.
import sys
def main():
try:
sys.exit(1)
finally:
print("cleanup still runs")
main()The program prints cleanup still runs and then exits with status 1.
The guarantee has limits. finally does not run in these cases:
os._exit()ends the process immediately, with no cleanup of any kind.- The process is killed from outside, for example by
SIGKILLor the Linux out-of-memory killer. - The machine loses power or the interpreter crashes.
- The
trybody never ends, for example an infinite loop or a deadlock. Thefinallyblock is simply never reached.
Generators and finally
A finally block inside a generator runs when the generator is closed. That happens when you call close(), when the generator is garbage collected, or when its for loop finishes. Python closes a generator by raising GeneratorExit at the paused yield, and the exception travels through your finally block. This is how @contextmanager works.
from contextlib import contextmanager
@contextmanager
def opened(path):
f = open(path)
try:
yield f
finally:
f.close()
with opened("notes.txt") as f:
first_line = f.readline()If the body of the with statement raises, the exception is thrown into the generator at the yield. The finally block closes the file, and the exception then continues upward.
Replacing try/finally with with
Most cleanup follows the same pattern: acquire, use, release. A context manager packages that pattern, and the with statement runs the release step for you. The earlier read_first_line function becomes shorter:
def read_first_line(path):
with open(path) as f:
return f.readline()This does the same work as the try/finally version. Prefer with whenever the resource supports it, which includes files, locks, sockets, and database connections in most libraries. Write try/finally yourself when no context manager exists, or when the cleanup is a one-off action such as restoring a setting.
A note on return, break, and continue
A return, break, or continue inside a finally block overrides whatever was pending, including a propagating exception, and the error disappears without a trace. The next chapter covers this in detail. For now, treat finally as a place for cleanup statements only.
Summary of rules
- Acquire the resource before the
try, and put only the guarded work inside it. - Use
try/finallywhen you need cleanup but cannot handle the error at this level. - Keep
finallyblocks short, and protect cleanup that can fail with its owntry/except. - Prefer a
withstatement when a context manager is available. - Do not put
return,break, orcontinueinfinally.
Exercise
What does this code print, and what does the caller receive? def f(): try: return "try" finally: print("cleanup") print(f())
Show answer
It prints cleanup first, then try. The return value is computed, then the finally block runs and prints, and only then does the function return "try" to the caller, so print(f()) prints it second.
Exercise
In the function below, open() raises FileNotFoundError because the file is missing. Which exception does the caller see, and how do you fix the function?
def first_line(path):
try:
f = open(path)
return f.readline()
finally:
f.close()
Show answer
The caller sees UnboundLocalError, because f was never assigned when finally ran. The FileNotFoundError is only visible as context. To fix it, move f = open(path) above the try, or use with open(path) as f:. Then a failed open() never reaches the finally block.