Module 12: Quick Reference
Error Handling Cheat Sheet
Common Error Types
| Error | Cause | Example |
|---|---|---|
SyntaxError | Invalid Python grammar | Missing colon, parenthesis |
NameError | Undefined variable/function | Typo in variable name |
TypeError | Wrong data type for operation | "hello" + 5 |
ValueError | Right type, wrong value | int("hello") |
IndexError | List index out of range | list[99] |
KeyError | Dictionary key not found | dict["missing"] |
FileNotFoundError | File does not exist | open("missing.txt") |
ZeroDivisionError | Division by zero | 10 / 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
- Read the error message (bottom up)
- Check the line number in the traceback
- Add
print()statements to trace values - Comment out code to isolate the bug
- Check for = vs ==, indentation, off-by-one errors
- Explain your code out loud (rubber duck debugging)
- 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.")