Files, Errors and Modules · Robust Code · lesson 1 of 8
Exceptions and try/except
about 14 minutes · free · runs in your browser
Step 1 of 2
Catching what goes wrong
When Python cannot do what you asked, it raises an exception. Uncaught, it stops the
program. try/except lets you decide instead:
try:
value = int(text)
except ValueError:
value = 0
Python runs the try block; if the named exception occurs it jumps to except.
The ones you will meet most:
| Exception | Cause |
|---|---|
ValueError | right type, wrong value — int("abc") |
TypeError | wrong type — "a" + 1 |
KeyError | missing dictionary key |
IndexError | list index out of range |
ZeroDivisionError | dividing by zero |
FileNotFoundError | opening something that is not there |
Name the exception you expect. A bare except: swallows everything, including the
typo in your own code, and turns a five-second bug into an afternoon.
Your turn: write to_int(text, fallback=0) returning the text as an integer, or the
fallback when it will not convert.
You start from this, and edit it in the browser:
def to_int(text, fallback=0):
# Convert to int, or return the fallback.
pass
Step 2 of 2
else and finally
Two more clauses complete the picture:
try:
result = risky()
except ValueError:
print("that failed")
else:
print("worked:", result) # only when nothing was raised
finally:
cleanup() # always, raised or not
else keeps the try block down to the single line that might fail, which makes it
obvious what you are actually guarding. finally runs whatever happens — including when
an exception is on its way up — so it is where cleanup belongs.
Your turn: write divide(a, b) returning a / b, or the string
"cannot divide by zero" when b is zero.
You start from this, and edit it in the browser:
def divide(a, b):
# Return a / b, or a message when b is zero.
pass