1.5 Hours

10. Error Handling & Debugging

Module 10: Error Handling

When things go wrong (and they will)

Every programmer deals with errors constantly — from beginners writing their first loop to senior engineers at major tech companies. The difference is experienced developers recognize errors faster and panic about them less. Here are the three types you'll encounter:

Syntax Errors

Python can't even read your code. You've violated the rules of the language itself — a missing colon, mismatched brackets, or a misspelled keyword:

Python 3
# Syntax Error examples
if True    # Missing colon → SyntaxError
    print('hello')

print('unclosed  # Missing closing quote → SyntaxError

Syntax errors are the easiest to fix — Python tells you exactly where they are. Fix the line it points to, or the line just before it.

Runtime Errors

The code looks fine, but something goes wrong while it's running. Common causes: dividing by zero, accessing a list index that doesn't exist, trying to open a file that doesn't exist:

Python 3
# Runtime Error examples
numbers = [1, 2, 3]
print(numbers[10])  # IndexError: list index out of range

x = 0
result = 10 / x     # ZeroDivisionError: division by zero

int('hello')        # ValueError: invalid literal for int()

Logical Errors

The code runs without crashing, but the output is wrong. These are the hardest to find because Python gives you no error message — the program just silently produces wrong results:

Python 3
# Logical Error example
def average(numbers):
    total = 0
    for n in numbers:
        total += n
    return total / 10  # BUG: should be len(numbers), not 10

print(average([5, 10, 15]))  # Returns 3.0, should be 10.0

Exception Handling — try/except

Instead of letting your program crash when an error occurs, you can catch the error and handle it gracefully:

Python 3
# Basic try/except
try:
    age = int(input('Enter your age: '))
    print(f'You are {age} years old.')
except ValueError:
    print('Please enter a valid number.')

# Multiple exception types
try:
    with open('data.txt', 'r') as f:
        content = f.read()
    number = int(content)
    result = 100 / number
except FileNotFoundError:
    print('Error: File not found.')
except ValueError:
    print('Error: File does not contain a valid number.')
except ZeroDivisionError:
    print('Error: Cannot divide by zero.')
except Exception as e:
    print(f'Unexpected error: {e}')
finally:
    print('This always runs — cleanup code goes here.')
finally Block

The finally block runs whether an exception occurred or not. Use it for cleanup operations: closing database connections, releasing file locks, logging.

Debugging Techniques

Debugging is the art of finding and fixing bugs. Here are the techniques professionals actually use:

1. Print Debugging
Add print statements to see what values your variables hold at different points. Simple, but surprisingly effective:

Python 3
def calculate_total(items):
    print(f'DEBUG: items received = {items}')  # Check input
    total = 0
    for item in items:
        print(f'DEBUG: processing {item}')    # Track progress
        total += item['price'] * item['quantity']
    print(f'DEBUG: total = {total}')          # Check output
    return total

2. VS Code Debugger
Set breakpoints (click the line number in VS Code) and step through your code line by line, inspecting variables at each step. This is far more powerful than print debugging for complex issues.

3. Reading Error Messages
Python's error messages are actually quite good. They tell you the error type, the line number, and a traceback showing what called what. Read them top to bottom, starting with the last line — that's usually where the actual problem is.

Logging Basics

For production code, replace print() with Python's logging module. It's more flexible, has severity levels, and can write to files:

Python 3
import logging

logging.basicConfig(level=logging.DEBUG)

logging.debug('Detailed information for diagnosing problems')
logging.info('Confirmation that things are working')
logging.warning('Something unexpected — program still works')
logging.error('Serious problem — function failed')
logging.critical('Program may not be able to continue')

Knowledge Check

Ready to test your understanding of 10. Error Handling & Debugging?

Back