Lesson 11 of 14 · 10 min

Exceptions

When something goes wrong, Python raises an exception: an error that stops the program, unless you handle it.

int("hello")    # ValueError: invalid literal for int() with base 10: 'hello'
10 / 0          # ZeroDivisionError: division by zero

try and except

Put risky code in try. If it raises, Python jumps to the matching except:

try:
    age = int(input("Age: "))
    print(f"Next year you will be {age + 1}")
except ValueError:
    print("That was not a number.")

You can catch several kinds, and get the error itself with as:

except (ValueError, TypeError) as error:
    print("Problem:", error)

Raising your own

When your function gets input it cannot work with, raise an exception with a clear message:

def set_speed(kmh):
    if kmh < 0:
        raise ValueError("Speed cannot be negative")
    return kmh

Catch exceptions where you know how to recover (ask again, use a default). Do not hide them with a bare except: that swallows everything.

Your task

  1. parse_quantity(text): convert to int and return it. If it is below 1, raise ValueError("Quantity must be at least 1"). (Text like "abc" already raises ValueError from int.)
  2. safe_divide(a, b): return a / b, or None if b is zero.
  3. ask_quantity(): keep asking with input("Quantity: ") until parse_quantity succeeds, then return the number. Print Try again after each bad answer.
main.py
def parse_quantity(text):
    pass


def safe_divide(a, b):
    pass


def ask_quantity():
    pass


print(safe_divide(9, 3))

Python 3.14 runs right here in your browser. The first run downloads about 10 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…