try, except, else, finally
Handling errors instead of crashing.
5 minute read
Big idea
try / except catches an exception so your program can handle it instead of crashing. else runs when nothing went wrong; finally runs no matter what.
The idea
try:
# code that might fail
except SomeError:
# what to do if it does
text = input()
try:
number = int(text)
print("Double is", number * 2)
except ValueError:
print(text, "isn't a whole number")
print("Still running")input
abcoutput
abc isn't a whole number
Still runningRun and edit it in the app.
Change the input to 21 and run again. When the try block succeeds, the except block is skipped.
Catch the specific error
Name the exception you expect. You can have several except blocks, and as e gives you the exception's message:
for a, b in [(10, 2), (5, 0), (7, "x")]:
try:
print(a / b)
except ZeroDivisionError:
print("can't divide by zero")
except TypeError as e:
print("type problem:", e)What does it print? Show the answer
5.0
can't divide by zero
type problem: unsupported operand type(s) for /: 'int' and 'str'Run and edit it in the app.
A bare except: (with no type) catches everything, including typos in your own code — which hides bugs. Always name what you expect.
else and finally
def read_age(text):
try:
age = int(text)
except ValueError:
print("Not a number")
else:
print("Age is", age)
finally:
print("Checked", repr(text))
read_age("42")
read_age("forty")output
Age is 42
Checked '42'
Not a number
Checked 'forty'Run and edit it in the app.
else— runs only if thetryblock raised nothing. Keep the risky part intryand the "it worked" part inelse.finally— always runs: success, failure, even areturn. Used for cleanup, like closing a file.
Ask again until it's right
A common pattern: keep asking until the input is valid.
while True:
try:
n = int(input())
except ValueError:
print("Try again")
print("Got", n)input
ten
10output
Try again
Got 10Run and edit it in the app.
When int(...) succeeds nothing leaves the loop, so it reads past the end of the input. Add break after n = int(input()) (or in an else: block).
When does a finally block run?
Watch it
Think of it like
A trapeze act with a safety net. try is the jump. except is the net — it catches you if you fall. finally is taking a bow at the end, whatever happened.
Key terms
- try / except — Run code, and handle a named exception if it's raised.
- else — Runs when the try block raised nothing.
- finally — Always runs; used for cleanup.
Check yourself
When does the except block run?
Why avoid a bare except:?
When does the else block of a try run?