10. Error Handling & Debugging
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:
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:
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:
Exception Handling — try/except
Instead of letting your program crash when an error occurs, you can catch the error and handle it gracefully:
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:
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:
Knowledge Check
Ready to test your understanding of 10. Error Handling & Debugging?