Python Else & Finally
else and finally are extra blocks after a try block.
Different errors, different blocks
Each except block waits for its own error type.
try:
number = int("abc")
print(number)
except ValueError:
print("Bad value")
except TypeError:
print("Bad type")Else runs after success
Nothing went wrong, so else runs.
try:
number = int("42")
except ValueError:
print("Bad value")
else:
print("Got", number)Else is skipped after failure
Something went wrong, so else does not run.
try:
number = int("abc")
except ValueError:
print("Bad value")
else:
print("Got", number)Finally always runs
Finally runs after the try block finishes.
try:
print("Trying")
except ValueError:
print("Bad value")
finally:
print("Cleanup time")Example
with open("report.txt", "w") as file:
file.write("Sales are up")
try:
with open("report.txt") as file:
text = file.read()
except FileNotFoundError:
print("No file found")
else:
print("Report:", text)
finally:
print("done")Key points
- Use a separate except block for each error type
- Use else for code that should run only on success
- Use finally for code that must always run
- Closing files is the classic finally job from file work
In this example, the program first writes a short report file. It uses with, so that file closes by itself. Next, it opens the report again inside try. The read works, so the except block is skipped. The else block prints the report text. The finally block prints done at the end. finally would print done even if the file were missing.
Note
finally runs even when an error was raised.
It also runs when the try block succeeds.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which block runs whether the try block worked or failed?