Python · Stage 7 – Files and Errors · Lesson 40 of 50

Handling Errors with try and except

Handle one expected exception and continue with a helpful message.

try:
    age = int("twelve")
except ValueError:
    print("Please enter digits")
Line-by-line explanation
  1. Try begins the protected block.
  2. The conversion raises ValueError.
  3. The matching except block catches it.
  4. A helpful message is displayed instead of a traceback.

Catch only exceptions you understand and can handle. Unexpected programming bugs should remain visible.