All lessons

Leveling up · step 19 of 22

Errors & exceptions

10 minCatch problems instead of crashing, and read the messages Python sends.

When things go wrong at runtime

A syntax error means Python could not read your code at all. A runtime error happens while the code runs:

  • ValueError — int("abc"): the text is not a number
  • TypeError — "5" + 5: mixing text and numbers
  • ZeroDivisionError — dividing by zero

Handling them yourself

try runs the risky lines; if one fails, except catches that error instead of crashing the program.

answer = "42"
try:
    number = int(answer)
    print(number + 8)
except ValueError:
    print("That was not a number")

Catch the error you expect rather than everything, and wrap only the lines that can fail — that keeps the rest of your program honest about real bugs.

else and finally

else runs when nothing went wrong; finally runs either way, which is where cleanup belongs.

try:
    value = int("7")
except ValueError:
    print("Bad input")
else:
    print(value * 2)     # 14

Remember this

  • Runtime errors are messages raised while the code runs
  • try/except handles an expected error instead of crashing
  • Catch the specific error and only wrap the risky lines

Quick quiz

Three questions. 3 correct answers and you have the idea — you can retry as often as you like.

  1. 1. int('abc') raises which error?

  2. 2. What does except do?

  3. 3. How much code should a try block wrap?

Answer all three to check them.

Now write it yourself

0/2 passed
1

Practice 1

`text` is set for you and might hold something that is not a number. Convert it inside a try/except and print the number plus 8 — or print `Not a number` when the conversion fails.

practice_1.py

Given for you

text = "42"
2

Practice 2

Write a function `safe_divide(a, b)` that returns a / b, but returns `Cannot divide by zero` when b is 0.

practice_2.py

Finish with two of three quiz answers correct and every exercise passing, and this lesson is marked complete.