Bitpath

Lesson 1 · Unit 06

Exceptions

Read a traceback, then catch the errors you expect

13 exercisesabout 3 min

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 zero

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 str

Concept

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.

Python
for text in ["8", "eight"]:
    try:
        print(int(text) * 2)
    except ValueError:
        print(text, "is not a number")
# 16
# eight is not a number

Concept

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.

Python
try:
    n = int("42")
except ValueError:
    print("bad")
else:
    print("ok", n)
finally:
    print("always")
# ok 42
# always

9 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.

One email when Bitpath is ready to try. Nothing else. Privacy