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
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
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
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:
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:
try:
print("Working…")
finally:
print("Always runs")🧪 Practice: 2 steps
0 / 2 doneStep 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.
def to_int(text):
return int(text)
Output appears here. Press Run or Ctrl/⌘ + Enter.
Step 2 of 2 · Raise your own error
Write withdraw(balance, amount) that returns the new balance, but raises a ValueError with the message "Insufficient funds" if amount is more than balance.
def withdraw(balance, amount):
return balance - amount
Output appears here. Press Run or Ctrl/⌘ + Enter.
✅ Check your understanding
When does the code in an except block run?
Why catch a specific error like ValueError instead of every error?
Create a free account to track your progress.