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.

Tiny Practice

Handle invalid integer text with a clear message.

Starter template

try:
    number = int("no")
except CHANGE_ME:
    print("Not a number")
Line-by-line explanation
  1. The risky conversion is inside try.
  2. The exception name is missing.
Hint
  1. The conversion raises ValueError.
  2. Write the exception class without quotes.
  3. Keep the colon.
Show Solution
try:
    number = int("no")
except ValueError:
    print("Not a number")
Line-by-line explanation
  1. The conversion fails.
  2. ValueError matches the failure.
  3. The helpful message is displayed.