Learn Without Walls
← Back to Module 12

Module 12: Quick Reference

Error Handling Cheat Sheet

Common Error Types

ErrorCauseExample
SyntaxErrorInvalid Python grammarMissing colon, parenthesis
NameErrorUndefined variable/functionTypo in variable name
TypeErrorWrong data type for operation"hello" + 5
ValueErrorRight type, wrong valueint("hello")
IndexErrorList index out of rangelist[99]
KeyErrorDictionary key not founddict["missing"]
FileNotFoundErrorFile does not existopen("missing.txt")
ZeroDivisionErrorDivision by zero10 / 0

try / except / else / finally

try:
    # Code that might raise an error
    result = risky_operation()
except SpecificError as e:
    # Runs if SpecificError occurs
    print(f"Error: {e}")
except AnotherError:
    # Catches a different error type
    print("Different error!")
else:
    # Runs ONLY if no error occurred
    print("Success!")
finally:
    # ALWAYS runs (cleanup code)
    print("Done.")

Raising Exceptions

# Raise an exception
raise ValueError("Invalid input")

# Raise in a function
def validate(age):
    if age < 0:
        raise ValueError("Age cannot be negative")

Debugging Checklist

  1. Read the error message (bottom up)
  2. Check the line number in the traceback
  3. Add print() statements to trace values
  4. Comment out code to isolate the bug
  5. Check for = vs ==, indentation, off-by-one errors
  6. Explain your code out loud (rubber duck debugging)
  7. Take a break and come back fresh

Input Validation Pattern

while True:
    try:
        num = int(input("Enter a number: "))
        break  # Exit loop on success
    except ValueError:
        print("Invalid input. Try again.")