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 and exactly where.
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
Definition
Error Types in Python
Analogy
Definition
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 syntactically valid instruction. Also, a cook can taste the result, but code needs systematic testing.
Note
Three Errors, One Program
The same temperature converter can fail in all three ways:
# Syntax error: missing parenthesis
celsius = ((fahrenheit - 32) * 5 / 9
# SyntaxError: Python refuses to startPython cannot even run the code — the parenthesis is missing.
# Runtime error: user enters text instead of number
user_input = input("Temperature: ")
celsius = (int(user_input) - 32) * 5 / 9
# ValueError if user types "warm" instead of a numberThe code is syntactically correct but crashes when the input is not a number.
# Logic error: + instead of - (runs but wrong results)
celsius = (fahrenheit + 32) * 5 / 9
# No error, no crash, but the result is wrong!Python does not complain because the code is syntactically correct and executable. But the formula is wrong (+ instead of -), and the results are incorrect.
Caution
No Error Does Not Mean No Problem
The most dangerous misconception: "My code runs without error messages, so it must be correct." Logic errors produce no messages. Your code runs and produces results — they are just wrong. The only protection: test with known inputs and check whether the expected results come out.
Reading the Traceback: Your Error Map
Definition
Traceback
Analogy
Definition
The analogy breaks at an important point: A real crash report is read from top to bottom, with the most important part first. Python's traceback shows the most important part, the most recent call, at the bottom ("most recent call last"). That is why you must learn to read from bottom to top.
Note
Reading a Traceback: 4 Steps
- 1. Read the last line: error type and messagee.g. ValueError: invalid literal
- 2. Read the line above: which code line triggered the error?
- 3. Follow the call chain upward: which function called which?
- 4. Find the root cause: which function passed the problematic value?
Note
A Traceback in Practice
def get_age():
return int(input("Your age: ")) # user types "twenty"
def greet_user():
age = get_age()
print(f"You are {age} years old.")
greet_user()Traceback (most recent call last):
File "app.py", line 8, in <module> # 3. Program started here
greet_user()
File "app.py", line 5, in greet_user # 2. greet_user called get_age
age = get_age()
File "app.py", line 2, in get_age # 1. get_age crashed HERE
return int(input("Your age: "))
ValueError: invalid literal for int() with base 10: 'twenty'Read from the bottom: ValueError tells you the error type. The line above shows that int(input(...)) in get_age() crashed. The lines above trace the path: greet_user() called get_age(), and the main program called greet_user(). Newer Python versions (3.11 and later) add characters such as ^^^^ or ~~~^^ below some code lines that point to the exact expression that failed; the affected code line is then one line higher.
Caution
Do Not Edit Randomly
A common mistake: ignoring the traceback and editing code at random. The traceback tells you exactly where and what went wrong. Read it from bottom to top, and you save yourself hours of guessing.
Exception Handling: Writing Safety Nets
Definition
Exception Handling (try/except)
Analogy
Definition
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.
Note
The try/except Flow
- 1. try block executes: the "risky" code runs normally
- 2. Exception occurs: Python looks for a matching except block
- 3. except block responds: show error message, retry, or use default value
Note
Practice: Robust Input
def get_number(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("That's not a valid number. Try again.")
temperature = get_number("Temperature in Fahrenheit: ")
celsius = (temperature - 32) * 5 / 9
print(f"{temperature}°F = {celsius:.1f}°C")The function keeps asking for a number until the user provides a valid one. The try block attempts the conversion, and the except block catches the ValueError with a friendly message.
Caution
except: pass Is Dangerous
The most dangerous pattern in Python: except: pass. It silently swallows all errors, including real bugs like typos in variable names, making them invisible.
# DANGEROUS: swallows ALL errors
try:
result = calculate_price(item)
except:
pass # Silence. No error visible.
# CORRECT: catch only the expected error
try:
result = calculate_price(item)
except ValueError:
print("Invalid price, please check.")A bare except: pass catches everything — NameError (typos), TypeError (wrong arguments), and even KeyboardInterrupt (Ctrl+C). You will never know your code has a bug.
print() debugging: Add print() statements to check variable values at different points in your code. This lets you trace step by step where values diverge from what you expect.
assert statements: Write assert result > 0, "Result should be positive" in your code. If the condition is not met, Python crashes on purpose and shows you the spot. This turns silent logic errors into loud ones.
Rubber duck debugging: Explain your code line by line to an inanimate object (a rubber duck, a mug, a stuffed animal). The act of putting every step into words forces you to think through each step, and you often discover the error in the process.
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.
Note
Key Takeaways
- Python errors come in three types: syntax errors (code unreadable, caught before execution), runtime errors (code crashes, produces a traceback), and logic errors (code runs but produces wrong results — most dangerous because silent).
- A traceback is read from bottom to top: the last line names the error type, the line above shows the failing code, and the lines above trace the call chain.
- try/except blocks catch predictable errors and respond gracefully instead of crashing. Always catch specific exceptions like ValueError — never use bare except:.
- except: pass is the most dangerous pattern in Python — it silently swallows all errors, including real bugs, making them invisible and impossible to debug.
- "No error message" does not mean "no error." Logic errors produce correct-looking output that is subtly wrong. Always test with known inputs and expected outputs.
Check
Quiz: Debugging
Which error type runs without error messages but produces wrong results?
Select one answer
1. Which error type runs without error messages but produces wrong results?
2. You see this last line in a traceback: ValueError: invalid literal for int() with base 10: 'abc' What happened?
3. Which except block is the correct way to handle errors?
4. Your code outputs 0 instead of 100, with no error message. What is the best debugging strategy?
Check
Checkpoint: Do You Understand?
Can you explain this in your own words? Tick what you've got.
0 of 3 done