chapter 8.1

Error Handling

Catching and managing exceptions gracefully

Errors happen. Users enter bad data, files go missing, networks fail. Python uses exceptions — special objects that interrupt normal flow when something goes wrong. Instead of letting your program crash, you can catch exceptions and handle them.
# This would crash without error handling:
try:
    number = int("hello")
except ValueError:
    print("That's not a valid number!")

print("Program continues...")
The structure is: try the risky code, except catches specific errors:
◇info
Common exceptions you'll see:
ValueError — wrong type of value (int("abc"))
TypeError — wrong type used ("5" + 5)
IndexError — list index out of range
KeyError — dict key doesn't exist
ZeroDivisionError — dividing by zero
FileNotFoundError — file doesn't exist
You can catch multiple exception types and use else/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 numbers
⚠warning
Never use a bare except: with no exception type — it catches *everything*, including bugs you want to know about. Always specify what you're catching.
You can access the error message using as:
try:
    numbers = [1, 2, 3]
    print(numbers[10])
except IndexError as e:
    print(f"Error: {e}")
    # Error: list index out of range
Raising exceptions — sometimes *you* want to signal an error:
def 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}")
your turn
challenge

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...

output
$ Press RUN to execute your code
AI Tutor

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