Lesson 5 of 7 · 9 min · 2 hands-on steps

Handling Errors with try / except

Make programs that don't crash when the unexpected happens.

Errors stop programs

Python · try it
age = int("twenty")
print("This line never runs")

That's an exception: Python couldn't continue, so it stopped. In real apps, users type unexpected things, files go missing and networks fail. Good code expects that.

try / except

Python · try it
text = "twenty"
try:
    age = int(text)
    print(f"In 10 years you'll be {age + 10}")
except ValueError:
    print("Please enter your age as a number, like 25")

Python runs the try block. If a ValueError happens, it jumps to except instead of crashing.

Catch specific errors

Python · try it
def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return None

print(safe_divide(10, 2))
print(safe_divide(10, 0))

Avoid a bare except: that catches everything. It also hides real bugs, like a typo in a variable name, and makes them very hard to find.

Raising errors yourself

When your function gets input it can't handle, raise an error with a clear message:

Python · try it
def set_age(age):
    if age < 0:
        raise ValueError("Age can't be negative")
    return age

try:
    set_age(-5)
except ValueError as e:
    print("Problem:", e)

finally

finally runs no matter what. It's used for cleanup, like closing a file or a database connection:

Python · try it
try:
    print("Working…")
finally:
    print("Always runs")

🧪 Practice: 2 steps

0 / 2 done

Step 1 of 2 · Safe conversion

Write to_int(text) that returns the text converted to an int, or None if it can't be converted. Use try / except ValueError.

Python
def to_int(text):
    return int(text)

Output appears here. Press Run or Ctrl/⌘ + Enter.

✅ Check your understanding

  1. When does the code in an except block run?

  2. Why catch a specific error like ValueError instead of every error?

Create a free account to track your progress.