Paul's Python CoursePPC

try and except

Not met yet

try: runs a block that might fail. If a line in it fails, the rest of the block is skipped, and except ValueError: runs if the error was that kind; then the program carries on underneath. Add another except for each other error you expect. else: runs only if nothing went wrong, and finally: runs either way. Catch errors by name: except Exception: catches your own mistakes too, and hides them.

Try it

main.py
for text in ["12 / 4", "12 / 0", "twelve / 4"]:
    parts = text.split()
    try:
        answer = float(parts[0]) / float(parts[2])
    except ValueError:
        print("Not a number:", text)
    except ZeroDivisionError:
        print("Nothing divides by zero.")
    else:
        print("=", answer)

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks the rest of a try block still runs after the line that raised the error.
  • Thinks the program stops once an except block has run.
  • Thinks an error inside a try block still stops the program, even when a matching except is there.
  • Thinks a finally block runs only when there was no error.
  • Thinks finally runs once at the very end of the program, rather than each time its try block finishes.
  • Thinks except Exception only catches the errors you had in mind, so it's a safe default. It catches typos and other bugs too, and hides them.

Where it comes up