When Code Breaks
A guide for the moment when the program doesn't do what you wanted — which is almost always.
The moment your code produces a wall of red text for the first time, your instinct is to panic. But that red text — the traceback — is actually the most helpful thing Python can give you. It tells you exactly what went wrong, exactly where, and exactly why.
The real danger is not when Python screams at you — it is when Python says nothing at all but your results are quietly, subtly wrong. This article teaches you to classify Python errors into three types, read tracebacks like a detective reads a crash report, and write safety nets that keep your programs running.
Three Types of Errors
Error Types in Python
The recipe analogy breaks in two places: A real cook would question "200 kilograms of salt" — they have common sense. Python has no common sense and executes any logically valid instruction. Also, a cook can taste the result, but code needs systematic testing.
Three Errors, One Program
No Error Does Not Mean No Problem
Reading the Traceback: Your Error Map
Traceback
The analogy breaks at an important point: A real crash report is written chronologically from top to bottom. Python's traceback shows the most recent call at the bottom ("most recent call last"). That is why you must learn to read from bottom to top.
Reading a Traceback: 4 Steps
A Traceback in Practice
Do Not Edit Randomly
Exception Handling: Writing Safety Nets
Exception Handling (try/except)
The analogy breaks because a skydiver has exactly one reserve parachute, but Python allows multiple except blocks for different exception types — like separate reserves for different failure modes.
The try/except Flow
Practice: Robust Input
except: pass Is Dangerous
Deep Dive: Common Python Exceptions
Deep Dive: Debugging Strategies Without a Traceback
Interactive: What Is My Error?
Answer the questions in the diagnosis tree to find out which error type you are dealing with and which debugging strategy helps best. Notice how the three error types lead to different solution approaches.
What happens when you run your code?
Key Takeaways
Quiz: Debugging
Checkpoint: Do You Understand?
- Your code runs without error messages but prints 0 instead of 100. What type of error is this, and why is it particularly dangerous?
- You see a traceback whose last line reads "KeyError: 'name'". Where do you look first, and what do the lines above tell you?
- Write code that asks the user for a number and keeps asking until a valid input comes. Why is except: pass not a good solution here?