Catching and managing exceptions gracefully
# This would crash without error handling:
try:
number = int("hello")
except ValueError:
print("That's not a valid number!")
print("Program continues...")try the risky code, except catches specific errors:ValueError — wrong type of value (int("abc"))TypeError — wrong type used ("5" + 5)IndexError — list index out of rangeKeyError — dict key doesn't existZeroDivisionError — dividing by zeroFileNotFoundError — file doesn't existelse/finally:def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Can't divide by zero"
except TypeError:
return "Both values must be numbers"
else:
# Runs only if no exception occurred
return result
finally:
# Always runs, no matter what
print("Division attempted")
print(safe_divide(10, 3)) # 3.333...
print(safe_divide(10, 0)) # Can't divide by zero
print(safe_divide("x", 5)) # Both values must be numbersexcept: with no exception type — it catches *everything*, including bugs you want to know about. Always specify what you're catching.as:try:
numbers = [1, 2, 3]
print(numbers[10])
except IndexError as e:
print(f"Error: {e}")
# Error: list index out of rangedef set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age seems unrealistic")
return age
try:
set_age(-5)
except ValueError as e:
print(f"Invalid: {e}")Rewrite `get_item()` as `safe_get()` that: 1. Returns the item if the index is valid 2. Returns a helpful message if the index is out of range (`IndexError`) 3. Returns a helpful message if the index isn't a number (`TypeError`)
loading editor...
Ask about Error Handling
◇
Hey! I'm your AI tutor.
Ask me anything about this lesson, or paste code you're stuck on.
AI tutor is a premium feature