Sub topic 6
Sharing errors and stack traces
This chapter assumes you have used an AI chat or coding assistant, can run a Python file from a terminal, and can read a basic traceback. By the end you should be able to capture an error with the details an assistant needs to diagnose it, and to leave out the details it does not need.
Why the error is its own kind of context
A file shows what the code says. An error shows what the code did. The two can differ, and the difference is usually the bug. If you send only "it crashes", the assistant has to guess which line failed, which exception was raised, and what input triggered it. If you send the error, the assistant can start from facts.
Error output is also dense. A traceback is a short, structured report of the program's state at the moment of failure. It names a file, a line, a call chain, and an exception type. Because every part is useful, trimming it carelessly costs you more than it saves.
What a traceback contains
Take the small file used throughout this tutorial. It fails when given an empty list.
def average(values):
return sum(values) / len(values)
print(average([]))Running it produces this output.
Traceback (most recent call last):
File "stats.py", line 4, in <module>
print(average([]))
File "stats.py", line 2, in average
return sum(values) / len(values)
ZeroDivisionError: division by zeroRead it in three parts.
- The header.
Traceback (most recent call last):tells you the order of the frames below it. In Python, the oldest call comes first and the newest comes last. - The frames. Each frame is a pair of lines. The first gives the file, line number, and function name. The second shows the source text of that line. Here, the module called
averageon line 4, andaveragefailed on line 2. - The exception line.
ZeroDivisionError: division by zerois the last line. It gives the exception type and a message. This is the single most important line, and the one people most often forget to copy.
The deepest frame is the line where the error was raised. It is not always the line that caused the problem. Here, line 2 raised the error, but the cause is that line 4 passed an empty list. An assistant needs the whole chain to tell these apart.
What to include
A useful error report has five parts. Not every bug needs all five, but check each one before you send.
| Part | Why it helps | Example |
|---|---|---|
| The full traceback | Shows the call chain and the exception type | The block above, copied as text |
| The command you ran | Shows how the failure was triggered | `python stats.py` |
| The input or state | Often the real cause | `average([])` receives an empty list |
| What you expected | Separates a crash from a wrong result | "Return `None` instead of raising" |
| The environment, if relevant | Explains version-specific behavior | Python 3.12, Linux |
Copy the output as text. Do not retype it, and do not describe it from memory. A retyped traceback often loses a line number or changes a word, and the assistant will reason from your version.
Keep the whole traceback by default
It is tempting to send only the last line. Compare what each choice lets the assistant do.
- With only
ZeroDivisionError: division by zero, the assistant knows the kind of failure but not where. It can only suggest general fixes, such as "check for zero before dividing". - With the full traceback and the file, it can say that
len(values)is zero on line 2 because line 4 passes an empty list, and then propose a change that fits your code.
Send the last line alone only when the error is self-explanatory and you are asking a general question, such as what an exception type means.
Long tracebacks and noisy output
Real errors are often much longer than the example. Web frameworks, test runners, and libraries add many frames that you did not write. Sending all of it can fill the context budget with lines that do not matter.
Use these rules when output is long.
- Keep the first and last parts. The frames nearest your own code and the final exception line carry the most information.
- Drop repeated frames. If a recursion error shows the same three frames 900 times, keep a few cycles and note the count, for example "the previous 3 frames repeat about 900 times".
- Mark what you removed. Replace cut sections with a line such as
[... 40 frames from site-packages omitted ...]. This tells the assistant the trace is not complete. - Never rewrite the lines you keep. Cut whole frames, but leave each kept line exactly as it appeared.
Chained exceptions need extra care. Python prints messages such as During handling of the above exception, another exception occurred: when one error is raised while handling another. The first exception in the chain is often the real cause. If you copy only the last block, you lose it. Keep every block in the chain.
Errors that are not tracebacks
Not every failure is a Python traceback. Other kinds of output need slightly different handling.
- Compiler and linter messages. Include the file, line, and column the tool reports, plus the offending source line. Also say which tool and version produced the message, because rules differ between versions.
- Failing tests. Include the test name, the assertion message, and the diff or values the test runner prints. Add the test function itself, since the assistant cannot judge the failure without seeing what the test expects.
- Silent wrong results. There is no error to copy. Show the input, the actual output, and the expected output. These three items take the place of a traceback.
- Log lines. Include the lines just before the error, not only the line that says
ERROR. The earlier lines often show the state that led to it. - Intermittent failures. Say how often it fails and what differs between a passing and a failing run. A single traceback from a flaky failure can be misleading without that detail.
Pairing the error with code
An error without its source forces the assistant to guess at code it cannot see. The traceback tells it which files and lines matter, so you can use it to decide what else to share.
Look at the frames from the bottom up. Share the function in the deepest frame first. Then add the caller in the next frame up if the cause might be in the arguments it passed. In the example, the deepest frame is average, and the caller at line 4 supplies the empty list. Both are short, so share both.
Do not attach every file named in a long trace. Files inside libraries are rarely the problem, and the assistant usually knows the common ones. Share your own code first, and add library code only if you suspect the library itself.
Putting the error into a request
The error is one part of a request. The assistant also needs the file, the selection, and a clear task. A request that names the file, the selection, and the error, and then states the task and its constraints in a few lines, looks like this.
Context: stats.py (attached), selection: the average function (lines 1-2).
Error: ZeroDivisionError: division by zero when average([]) is called.
Task: Change average so an empty list returns None instead of raising. Keep the function signature and do not change other code.This request is short because the file is attached and the error is summarized in one line. For a bug that is harder to diagnose, paste the full traceback beneath the Error: line instead of summarizing it. The summary above works only because the exception is simple and the cause is visible in the selected function.
A good result for this request is a function like the following.
def average(values):
if not values:
return None
return sum(values) / len(values)
print(average([]))Running it prints None, and no exception is raised. That output is the check that the fix does what the task asked.
Removing sensitive details first
Errors often contain more than you expect. Before you paste one, scan it for the following.
- Absolute paths that include a user name, such as
/home/maria/projects/.... - Connection strings, tokens, and API keys. These appear in failed HTTP requests, database errors, and printed configuration.
- Email addresses, customer names, and other personal data in log lines or in the values shown by an assertion failure.
- Internal host names and IP addresses.
Replace each value with a placeholder that keeps the shape, such as <API_KEY> or /home/<user>/projects/app. A placeholder preserves the structure the assistant needs, and it keeps the secret out. If a key has already been pasted into a chat, treat it as exposed and rotate it.
When the error is not the whole story
A traceback points at where the program failed. It does not always show why. Watch for these cases.
- The fix works for the error but not the goal. Making
average([])returnNonestops the crash. If the caller then does arithmetic onNone, a newTypeErrorappears. Tell the assistant how the result is used. - The error is misleading. A
KeyErrormay come from a missing key, or from data loaded wrongly three steps earlier. If the assistant's first suggestion does not fit, add the code that produces the data. - The error changed. After a fix, you may get a different exception. Send the new one and say it replaced the old one. Do not keep the earlier trace in the conversation as if it were still current.
Each of these ties into refining context step by step, which a later chapter covers. The habit to build now is simple: send the new evidence, not a repeat of the old.
A checklist before you send
- Did I copy the error as text, including the final exception line?
- Did I keep chained exceptions together?
- Did I mark any frames I removed?
- Did I include the command, the input, and the expected result?
- Did I attach the code for the deepest frame and its caller?
- Did I replace secrets, user names, and personal data with placeholders?
Exercise
A teammate sends an assistant only the line KeyError: 'email' and asks, "Why does this fail?" Name three pieces of context the assistant still lacks, and say where each would come from.
Show answer
The assistant lacks (1) the full traceback, which shows which file and line raised the error and who called it; it comes from the terminal or log output, copied as text. (2) The code at the failing line and its caller, which shows which dictionary was read and how it was built; it comes from the files named in the deepest frames. (3) The input data or the command that triggered it, which shows whether the key is really missing or was lost earlier; it comes from the run that failed. The expected behavior would also help, such as whether a missing email should be skipped or reported.
Exercise
This is the end of a trace: "ValueError: invalid literal for int() with base 10: 'abc'", preceded by "During handling of the above exception, another exception occurred:" and an earlier block that ends in "FileNotFoundError: config.json". You plan to paste only the final ValueError block. Why is that risky, and what should you paste?
Show answer
The FileNotFoundError block is the first exception, and the ValueError was raised while the program was handling it. The original cause may be the missing config file, so the final block could be a side effect. Paste both blocks, in their original order and with the connecting line, so the assistant can see the whole chain.
Exercise
A function returns the wrong total but raises no exception. What should you send in place of a traceback?
Show answer
Send the input you gave the function, the actual output, and the output you expected, along with the function's code. These three values give the assistant the same starting facts that a traceback would give for a crash.