else and finally
A try can have two more blocks:
else:, after theexceptblocks, runs only when thetryblock raised no exception.finally:, at the very end, always runs: when everything went well, when an exception was caught, and even when an exception wasn't caught and the program is about to end.
age_text = "15"
try:
age = int(age_text)
except ValueError:
print("The age must be a number.")
else:
print("Next year you'll be", age + 1)
finally:
print("Form checked.")Next year you'll be 16
Form checked.With age_text = "fifteen", the program prints The age must be a number. and Form checked. The else block is skipped, the finally block isn't.
Why else, when you could put the print() into the try block? Keep in the try block only the line you expect to fail. A long try block also catches a ValueError from a line where you didn't expect one, and that mistake then gets lost behind your message, as with the bare except:. The else block is for what should happen once the risky line has worked.
And why finally, when a line after the whole try runs anyway? Not always: when an exception isn't caught, the program ends, and the lines after it never run. A finally block runs even then, just before the program ends:
try:
print(10 / 0)
finally:
print("This runs anyway.")This runs anyway.
Traceback (most recent call last):
File "<exec>", line 2, in <module>
ZeroDivisionError: division by zeroPrograms use it for what has to happen whatever goes wrong, such as saving work or closing a file. In short programs, you'll rarely need it, but you'll meet it in other people's code.
The order is always the same: try, the except blocks, else, finally. You can leave out else and finally.
Instructions
- 1
The booking form has received the number of nights. Add an
elseblock that prints the price of the stay. A night costs $25, so the program printsTo pay: $75. Try it with"three"in place of"3", and then change it back. - 2
Below the
elseblock, add afinallyblock that printsBooking checked.Whatever the form received, it's the last line of the output.