Lesson 1 · Unit 06
Exceptions
Read a traceback, then catch the errors you expect
What you practise
- Reading a traceback from the bottom,
try,except,else,finally,raise, catching the narrowest error, errors against bugs
Try a question from this lesson
Pick one
A program stopped and Python printed this report, called a traceback. Read its last line first. Why did the program stop?
Traceback (most recent call last):
File "report.py", line 5, in <module>
print(average(scores))
~~~~~~~^^^^^^^^
File "report.py", line 2, in average
return sum(nums) / len(nums)
~~~~~~~~~~^~~~~~~~~~~
ZeroDivisionError: division by zeroCorrect answer
It divided a number by zero
Why
The last line always names the kind of error and says what happened: here, a division by zero. The lines above it show where. The list handed to the function was empty, so its length was 0.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Read a traceback from the bottom
An error that stops a program is called an exception. The report Python prints is a traceback.
The last line is the kind of error and a message. Above it, each File entry is one step on the way: the call at the top led to the call below it. The entry closest to the bottom is the line that failed.
Traceback (most recent call last):
File "shop.py", line 9, in <module>
total = add(price, 2)
File "shop.py", line 2, in add
return a + b
~~^~~
TypeError: can only concatenate str
(not "int") to strConcept
try and except
Put the lines that might fail under try. Name the error you expect after except.
No error: the except block is skipped.
An error of that kind: the rest of the try block is skipped, the except block runs, and the program carries on below.
for text in ["8", "eight"]:
try:
print(int(text) * 2)
except ValueError:
print(text, "is not a number")
# 16
# eight is not a numberConcept
else and finally
Two more blocks can follow except.
else runs only when the try block finished without an error.
finally runs every time, error or not. Use it for tidying up that must always happen.
try:
n = int("42")
except ValueError:
print("bad")
else:
print("ok", n)
finally:
print("always")
# ok 42
# always9 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× true or false
- 1× fill the blanks
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.