try and except

phrase

say it: “TRY and ik-SEPT” /traɪ ænd ɪkˈsɛpt/

Python's way to handle errors: code that might fail goes under try, and code under except runs if that error happens, instead of the program crashing.

What do try and except do?

try runs code that might fail; except catches the error and decides what to do instead of crashing.

try:
    age = int(input("Age: "))
except ValueError:
    print("Please type a number")

In a sentence

  • “try and except caught the ValueError when the user typed "twelve" for their age.”
  • “Wrap the file read in try and except so a missing file shows a friendly message.”

Level: Journeyman · More Python terms at this level

Updated