Start free

A level · 4 exercises

Python exceptions

A try block runs code that might fail; its except catches the error and lets the program carry on, instead of stopping.

Catch the error you expect, by name: ValueError for int("abc"), ZeroDivisionError for dividing by 0.

for line in ["4", "x", "7"]:
    try:
        print(int(line) * 2)
    except ValueError:
        print("not a number")

Watch for: A bare except: hides every mistake, your own typing errors too. Name the error.

Exercises

  1. Safe divisionDivide pairs of values.Advanced
  2. Count the bad linesRead lines until the line END.Advanced
  3. Real datesCheck dates written as YYYY-MM-DD.Advanced
  4. Careful calculatorWork out expressions "a op b" where op is +, -, * or /.Advanced
Start with “Safe division”