Errors travel up
🌍 In real life. A problem on a factory floor goes up the chain: a worker reports it to the supervisor; if the supervisor can't fix it, it goes to the manager, and then to the owner. Whoever can deal with it does, and the people above never hear about it. If nobody can, the whole factory stops.
An error in Python travels up the chain of function calls the same way.
The idea in one sentence: an error raised inside a function travels up the call stack, out of each function in turn, until some try catches it, or the program stops with a traceback listing every call it passed through.
Its words:
- propagate: travel up from the function where the error started
- traceback: the list of calls the error passed through, oldest first, the error itself last
- unmatched except: an
exceptfor a different error; it doesn't stop this one
Step by step, for total(["3", "4", "x"]) inside a try:
totalcallsread_score("x"), andint("x")raises a ValueError.read_scorehas no try, so the error leaves it and arrives intotal.totalhas no try either, so it leavestotaltoo.- The
tryaroundtotal(...)catches it, and prints "Couldn't add them up".
def read_score(text):
return int(text)
def total(texts):
result = 0
for t in texts:
result += read_score(t)
return result
try:
print(total(["3", "4", "x"]))
except ValueError as e:
print("Couldn't add them up:", e)def read_score(text):
return int(text)
def total(texts):
result = 0
for t in texts:
result += read_score(t)
return result
print(total(["3", "4", "x"]))An except that doesn't match doesn't stop the error either: finally still runs, and then the error keeps travelling.
Two styles: check first (if key in d:) or try it and catch (try: d[key]). Both are fine. Try-and-catch shines when checking first is hard, like "is this text a valid number?"
Why errors travel. The function where a problem happens often doesn't know what to do about it: read_score can't decide whether a bad score should skip a student or stop the report. Letting the error travel means the decision is made at the level that does know, and the functions below stay simple.
Mistakes and edge cases.
- Reading a traceback from the top only. Start at the last line (the error), then read upward through the calls to see how it got there (Lesson 7.7).
- Catching too low. A try deep inside
read_scorethat prints and returns 0 would hide the bad score fromtotal; catch where you can make a sensible choice. - Assuming finally stops it. It runs, and then the error carries on up.
- A loop that dies on one bad item. If one bad value shouldn't stop the rest, put the try inside the loop.
Quiz
What does this print?
def inner(): return 1 / 0 def outer(): print("start") inner() print("never") try: outer() except ZeroDivisionError: print("caught")An error is raised inside a function, and that function has no try. What happens next?
- It travels up to the code that called the function
- The function returns None
- Python skips that line and carries on
What does this print?
def parse(words): numbers = [] for w in words: try: numbers.append(int(w)) except ValueError: pass return numbers print(parse(["1", "two", "3"]))What does this print?
ages = {"Ana": 9} for name in ["Ana", "Bo"]: try: print(ages[name]) except KeyError: print(name, "unknown")Which line has a mistake?
def read_number(text): try: return int(text) except ValueError: print("Not a number") print(read_number("x") + 1)
Coding tasks
Write
parse_all(words)that returns a list of the words that are whole numbers, as numbers, skipping the rest.Write
first_number(words)that returns the first word that is a whole number, as a number. If none is, raise aValueError.Write
sum_valid(text)that adds up the whole numbers in a comma-separated text, ignoring parts that aren't numbers.sum_valid("1,x,3")is 4.