LESSON 11

Errors

Learning objective: Handle errors gracefully with try and except.

Understand

Errors are normal; good code handles them.

Wrap risky code in try and catch problems with except so your program does not crash. You can handle specific error types and give the user a helpful message instead.

Analogy: Try/except is like a safety net that catches a fall instead of letting the program crash.

See It in Action

Catching a bad conversion:

try:
    n = int("abc")
except ValueError:
    print("Please enter a number.")
How it works: Converting 'abc' to an int fails, so the except block runs and shows a friendly message instead of crashing.

Try It Yourself

  1. Write code that could fail, like int(input()).
  2. Wrap it in try/except.
  3. Show a helpful message on error.

Quick Quiz

What does except do?

Challenge

Ask for a number and handle the case where the user types text.

Success condition: Your program stays running and shows a helpful message on bad input.