Sub topic 1
Read the error before you ask
An error message is the most precise evidence you have about a failure. An assistant can only work from what you give it, and a pasted traceback you have not read often leads to a vague question and a vague answer. This chapter covers how to read an error yourself, so you can tell what the assistant should look at and check its answer later.
Prerequisites
This chapter assumes you can:
- Write and run small programs in Python or JavaScript. The examples use Python 3.
- Run a script or test from a terminal or IDE and see its output.
- Read a function definition and follow a call from one function to another.
You don't need to have used an AI assistant yet. Later chapters cover prompts, diagnosis, and fixes.
Why read the error first
Reading the error before you ask has three benefits:
- You often find the cause yourself. Many errors name the problem directly, and the fix takes a minute.
- You ask a better question. "Why does line 2 divide by zero when the list is empty?" gets a sharper answer than "my code is broken".
- You can judge the answer. If you know what the traceback says, you can tell when the assistant's diagnosis contradicts it. Chapter 6 builds on this.
Reading is not the same as understanding everything. The goal is a short, written hypothesis: what failed, where, and what you suspect.
The anatomy of a traceback
Start with a small failing program.
def average(values):
return sum(values) / len(values)
print(average([]))Running it as stats.py produces this output:
Traceback (most recent call last):
File "stats.py", line 5, in <module>
print(average([]))
File "stats.py", line 2, in average
return sum(values) / len(values)
ZeroDivisionError: division by zeroA Python traceback has three parts:
- The header.
Traceback (most recent call last)tells you the order of the frames. Python prints the oldest call first and the newest last. - The frames. Each frame is a file, a line number, and a function name, followed by the source line. The frames form the call stack, which is the chain of calls that led to the failure. Here
<module>calledaverage. - The final line. It gives the exception type (
ZeroDivisionError) and a message (division by zero).
Python puts the final line last, which is also where the failure happened. In a long trace, start at the bottom and read upward.
A reading order that works
Use the same order every time.
Apply it to the example:
- Last line:
ZeroDivisionError: division by zero. Some division had a denominator of zero. - Last frame in your code:
stats.py, line 2, inaverage. - Source line:
return sum(values) / len(values). There is only one division here, so the denominator islen(values). - Values:
len(values)is zero only whenvaluesis empty. The call on line 5 passed[]. - Hypothesis:
averagefails when given an empty list. It never checks for that case.
You now know the cause without any help. Asking the assistant is still useful for the design question: should the function return None, return 0, or raise a clearer error?
What the error type tells you
The exception type puts the failure in a category before you read any code. This table lists common Python types and what to check first.
| Error type | Usual meaning | First thing to check |
|---|---|---|
| `TypeError` | An operation got a value of the wrong type | The types of the operands, often `None` or a string where a number was expected |
| `ValueError` | The type is right but the value is not | The input value and the function's accepted range |
| `KeyError` | A dictionary lookup used a missing key | The key's spelling and where the dictionary was built |
| `IndexError` | A sequence index is out of range | The length of the sequence and off-by-one errors |
| `AttributeError` | The object has no such attribute | Whether the object is `None` or a different class than you expected |
| `ImportError` / `ModuleNotFoundError` | A module or name could not be imported | The active environment, installed packages, and the file name |
| `ZeroDivisionError` | The denominator was zero | Empty collections and unset counters |
The message adds the detail. AttributeError: 'NoneType' object has no attribute 'strip' says an earlier call returned None. The bug is usually in that earlier call, not on the .strip() line.
Where it failed and where the bug is
The last frame shows where the failure surfaced. The bug may be somewhere else.
In the average example both are the same, because the function has no guard. Consider a variation:
def parse_scores(text):
return [int(part) for part in text.split(",") if part]
def report(text):
scores = parse_scores(text)
return sum(scores) / len(scores)
print(report(""))This also raises ZeroDivisionError on the line in report. The cause is that parse_scores("") returns an empty list, and report assumed there was at least one score. Whether to fix report or add validation upstream is a design choice. Treat the traceback as the start of the investigation, not a verdict.
Two rules help:
- If the failing line is in your code, ask which value on that line is not what you assumed, then trace where that value came from.
- If the failing line is in a library, scroll up to the last frame that is in your code. That frame is usually where you passed in something the library did not expect.
Chained exceptions
Python sometimes prints two tracebacks. This happens when one exception is raised while handling another, or when code uses raise ... from ....
def load_port(config):
try:
return int(config["port"])
except KeyError as exc:
raise RuntimeError("config is missing a port") from exc
load_port({})The output has two sections:
Traceback (most recent call last):
File "config.py", line 3, in load_port
return int(config["port"])
KeyError: 'port'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "config.py", line 8, in <module>
load_port({})
File "config.py", line 5, in load_port
raise RuntimeError("config is missing a port") from exc
RuntimeError: config is missing a portThe first traceback holds the original cause, the KeyError. The second holds the error your code chose to raise. When you see the phrase "direct cause", read the first section as the root and the second as the report. If the text says "During handling of the above exception, another exception occurred", the second error was probably an accident inside an except block, and it can hide the original problem.
Other languages
The ideas carry over, but the layout differs.
- JavaScript (Node.js): the message comes first, for example
TypeError: Cannot read properties of undefined (reading 'name'). The stack follows with the most recent call at the top. Read top-down, and skip frames fromnode_modulesornode:internaluntil you reach your own files. - Java: the exception and message come first, followed by
atlines with the most recent call first. ACaused by:line near the bottom is the root cause, and it usually matters more than the first line. - Compilers and type checkers: errors such as
cannot find symbolorerror TS2322give a file, line, and column. Fix the first error before the others, because later ones are often side effects.
Always check which direction the stack runs before you decide which frame is the newest.
Common reading mistakes
- Reading only the last line. The type and message tell you what, but not where.
- Blaming the library. Libraries have bugs, but a wrong argument from your code is much more likely.
- Fixing the symptom. Wrapping the failing line in
try/exceptremoves the error without fixing the empty list or theNonethat caused it. - Trusting the line number blindly. After you edit a file, the traceback may refer to an older version. Re-run before you read.
- Truncating the output. Paste the complete trace, because a missing section is hard to recover later.
- Ignoring warnings printed just before the error. A
DeprecationWarningor a failed import message sometimes explains the crash.
Write down your hypothesis
Before you ask the assistant anything, write one or two sentences in plain text. For the first example they might be:
average() fails at stats.py line 2 because len(values) is 0 for an empty list.
I expect the caller to be told that the input is empty.This note is useful for three reasons. It forces you to read the trace. It becomes the opening of your prompt, which Chapter 5 covers. And it gives you something to compare with the assistant's answer. If the assistant proposes a cause that doesn't match your reading, you know to look closer at one of you.
Exercises
Exercise
A Python traceback ends with AttributeError: 'NoneType' object has no attribute 'strip', and the failing line is name = user.get_name().strip(). Which part of the code is the most likely source of the bug, and why?
Show answer
The call user.get_name() returned None, so the bug is probably inside get_name or in the way user was set up, not in the .strip() call. The error type and message say that the object is None, and the failing line only shows where the None was used.
Exercise
You see two tracebacks. The first ends with KeyError: 'port'. Between them is the text "The above exception was the direct cause of the following exception", and the second ends with RuntimeError: config is missing a port. Which one do you treat as the root cause, and what do you paste into a prompt?
Show answer
The KeyError in the first traceback is the root cause. The RuntimeError is the error the code raised in response. Paste both tracebacks and the connecting text, so the assistant sees the whole chain.
Exercise
In report("") from the parse_scores example, the traceback points at return sum(scores) / len(scores). Write a one-sentence hypothesis in the form "what failed, where, and why".
Show answer
report raises ZeroDivisionError on its division line because parse_scores("") returns an empty list, so len(scores) is 0.