Skip to the content

try and except

Python · Unit 9: Errors and exceptions

try tries a block. If an error of the type you name in except crashes in there, Python doesn't stop: it jumps to the except and then carries on with what's below.

try:
    print(10 / 0)
except ZeroDivisionError:
    print("Can't divide by 0")
print("The program goes on")

Prints

Can't divide by 0
The program goes on

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Complete the code

    The person types three, in letters. Complete it so the program doesn't crash.

  4. 4. Complete the code

    Complete it so it warns you instead of crashing.

  5. 5. Find the bug

    This program should say there's no third number. Which line has the bug?

  6. 6. Multiple choice

    text is a number, but the program says «Numbers only». Why?

  7. 7. Predict the output

    The person types ten, in letters. What does it print?

  8. 8. Put the lines in order

    The person types two, in letters, and then 2. Put the program in order so it asks for tickets until it gets a number.

  9. 9. Find the case that fails

    to_int(t) should turn the text into a whole number, or return 0 if it isn't a number. Which call breaks it?

  10. 10. Predict the output

    There's a typo in the list. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →