🛟 Errors & Exceptions, lesson 4 of 6
else and finally
Run code only on success, and clean up no matter what.
8 min
1 exercise
1 quiz
0/2 solved
Getting Python ready… examples can run in a moment.
A try statement has two optional extra parts:
- else runs only if the try block raised no exception. Put your "success" code here so the try block stays small.
- finally runs always: after success, after a
handled error, even after
return. Use it for cleanup.
try:
risky()
except ValueError:
handle_it()
else:
on_success()
finally:
clean_up()
Watch the order
Add attempt("") at the end. Which blocks run?
What does this print?
finally even beats return. If a function returns
from inside try, the finally block still runs
before the function exits. If an error is not
caught, finally runs first and then the error keeps
travelling up.
finally runs before the return completes
"Closing settings." appears before "dark". Now look
up a missing key like "font": the cleanup still
prints, then the KeyError crashes the program.
Files, with, and else
Change the second file name to "todo.txt" (a file
that doesn't exist) to trigger the except branch.
A safe average with a call log
safe_average([]) crashes. Rewrite the function with
all four parts:
- try: compute
sum(nums) / len(nums) - except ZeroDivisionError: return
None - else: return the average rounded to 1 decimal
- finally: append
len(nums)tocalls