Lesson 11: Error Handling with try/except

How Python manages and recovers from runtime errors

Why Error Handling Matters

Errors happen — missing files, invalid input, network issues, or unexpected data. Without handling them, your program may crash. Python’s try/except system lets you catch and respond to errors gracefully.

The try/except Structure

The basic pattern looks like this:

try:
    # Code that might fail
    risky_operation()
except:
    # Code that runs if an error occurs
    print("Something went wrong!")

Catching Specific Exceptions

It’s best practice to catch specific error types:

try:
    number = int("abc")
except ValueError:
    print("Invalid number!")

Multiple Except Blocks

You can handle different errors differently:

try:
    file = open("data.txt")
    value = int(file.read())
except FileNotFoundError:
    print("File not found.")
except ValueError:
    print("File does not contain a valid number.")

Using else

The else block runs only if no exception occurs:

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("Success:", result)

Using finally

The finally block always runs, whether an error occurred or not:

try:
    file = open("example.txt")
    content = file.read()
except FileNotFoundError:
    print("File missing.")
finally:
    print("Done trying to read the file.")

Raising Your Own Exceptions

You can trigger errors intentionally using raise:

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative.")
    return age

Common Exceptions

Best Practices

Next Steps

Now that you understand error handling, you're ready to explore object‑oriented programming in Lesson 12: Object‑Oriented Programming Basics.

← Back to Lesson Index