Python try and finally: code that always runs
The finally block runs when the try block ends, with or without an error, and also when return leaves the function.
Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.
TE-100-A: finally runs after a normal return and after an uncaught-in-function error that the caller catches
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
def f(fail):
try:
if fail:
raise ValueError('x')
return 'ok'
finally:
print('cleanup', fail)
print(f(False))
try:
f(True)
except ValueError:
print('caught')
EOSCommand:
python3 s.pyRecorded output:
cleanup False
ok
cleanup True
caughtExit status: 0. The output matches the expected text written before the run.
TE-100-B: a return inside finally replaces the value returned by the try block
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
def f():
try:
return 'try'
finally:
return 'finally'
print(f())
EOSCommand:
python3 s.pyRecorded output:
finallyExit status: 0. This status and the output match what was written before the run.
TE-100-C: expected non-zero exit: finally runs, and then an error that nothing catches ends the program with exit status 1
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
try:
raise ValueError('x')
finally:
print('cleanup')
EOSCommand:
python3 s.pyRecorded output:
cleanupStandard error from the same run:
Traceback (most recent call last):
File "/tmp/b24-unmfv0av/work/s.py", line 2, in <module>
raise ValueError('x')
ValueError: xExit status: 1. This status and the output match what was written before the run. The path in the traceback line is a temporary folder and differs on each machine and each run.
TE-100-B: the try block returned try, but finally ran next and its own return won, so the function returned finally. TE-100-C: finally printed cleanup, and then the ValueError that nothing caught ended the program with exit status 1. The last line of standard error is ValueError: x.
Limits
Only one function and one error type were run. TE-100-B runs one return inside finally. Not tested on this page: a break or continue statement inside finally, a finally clause that raises a second exception (the language reference topic for the try statement, from Python 3.10.12, says the saved exception then becomes the context of the new one), and a break or continue in the try suite of a try and finally statement with no exception. No run here used these cases. The reference topic also describes an else clause, an except without an expression that must come last, and sys.exc_info(); none of these was run. Only except ValueError was run, in TE-100-A.
Source
Evidence table
| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-100-A | finally runs after a normal return and after an uncaught-in-function error that the caller catches | 0 | PASS | 6fd410d7af68 | | TE-100-B | a return inside finally replaces the value returned by the try block | 0 | PASS | 833ecd386961 | | TE-100-C | expected non-zero exit: finally runs, and then an error that nothing catches ends the program with exit status 1 | 1 | PASS | 99c0b49fed0d |
Recorded on: bash 5.1.16(1)-release; git version 2.34.1; Python 3.10.12. Locale C.UTF-8, TZ=UTC. Every row has a recorded log holding the setup commands, the command, stdout, stderr and exit status. The first 12 characters of the log's sha256 are in the table.
All full guides: All guides