One-Line Definition
A stack trace records the call locations an exception passes through as it unwinds; reading the exception type, message, and exception chain together lets you trace a failure from the crash site back to its underlying trigger.
Why It Matters
- It is your single most valuable debugging clue—and the runtime gives it to you automatically without extra instrumentation.
- Knowing how to read it saves hours: Beginners often panic at a wall of red traceback output, even though the immediate failure is summarized right on the bottom line.
- It is the first artifact you should attach when asking a teammate (or an AI assistant) for help.
Usage Boundaries
The final line summarizes the currently raised exception, which is not always the underlying root cause. Library frames, chained exceptions, and asynchronous device errors can all hold vital clues and should be read alongside input data and call context.
How It Works / Diagram
Every function call pushes a stack frame onto the call stack (recording the function name, file path, line number, and local state). When an unhandled exception occurs, Python prints the active frames from the outermost caller down to the innermost failure point:
Three-step reading sequence:
- Start at the very bottom line: Read the exception type and message (e.g.,
RuntimeError: Invalid config file format). - Scan upward for frames in your own code: Your own modules are the most common starting point, though library frames and malformed inputs often reveal why the call failed.
- Check for chained exceptions:
"The above exception was the direct cause of the following exception"indicates an explicit causal chain created viaraise ... from e;"During handling of the above exception, another exception occurred"means a second error was triggered inside anexceptorfinallyblock.
Starting in Python 3.11, tracebacks underline the exact failing sub-expression with ~~~^^^ markers (PEP 657): https://peps.python.org/pep-0657/; see also the traceback module docs: https://docs.python.org/3/library/traceback.html
Runnable Example
A trailing-comma JSON syntax error wrapped across two call layers with raise ... from e, plus programmatic frame inspection via the traceback module (verified on Python 3.15.0):
# File: examples/15_stack_trace.py
# Reading a Stack Trace bottom-up and preserving causal exception chains (raise ... from ...)
import traceback, json
def parse_config(text):
return json.loads(text)
def load_settings(text):
try:
cfg = parse_config(text)
except json.JSONDecodeError as e:
raise RuntimeError("Invalid config file format") from e # Preserve original root cause
return cfg["model"]
def main():
return load_settings('{"model": "deepseek",}') # Extra trailing comma
try:
main()
except RuntimeError:
tb = traceback.format_exc()
print(tb.replace(__file__, "15_stack_trace.py"))
# Inspect stack frames programmatically (how logging and APM tools extract failure locations)
try:
main()
except RuntimeError as e:
frames = traceback.extract_tb(e.__traceback__)
last = frames[-1]
print("Innermost frame:", last.name, "line", last.lineno)
print("Root cause type:", type(e.__cause__).__name__)
Recorded output (Python interpreter path abbreviated as <python3.15>):
Traceback (most recent call last):
File "15_stack_trace.py", line 9, in load_settings
cfg = parse_config(text)
File "15_stack_trace.py", line 5, in parse_config
return json.loads(text)
~~~~~~~~~~^^^^^^
File "<python3.15>/lib/python3.15/json/__init__.py", line 371, in loads
return _default_decoder.decode(s)
~~~~~~~~~~~~~~~~~~~~~~~^^^
File "<python3.15>/lib/python3.15/json/decoder.py", line 358, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
File "<python3.15>/lib/python3.15/json/decoder.py", line 374, in raw_decode
obj, end = self.scan_once(s, idx)
~~~~~~~~~~~~~~^^^^^^^^
json.decoder.JSONDecodeError: Illegal trailing comma before end of object: line 1 column 21 (char 20)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "15_stack_trace.py", line 18, in <module>
main()
~~~~^^
File "15_stack_trace.py", line 15, in main
return load_settings('{"model": "deepseek",}') # Extra trailing comma
File "15_stack_trace.py", line 11, in load_settings
raise RuntimeError("Invalid config file format") from e # Preserve original root cause
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Invalid config file format
Innermost frame: load_settings line 11
Root cause type: JSONDecodeError
Key details to notice:
- The
~~~~~~~~~~^^^^^^underline pinpoints the exact sub-expression that raised. JSONDecodeErrorreports the exact line, column, and character offset of the illegal trailing comma (exact wording can vary slightly across Python releases).- Using
from ekeeps the originalJSONDecodeErrorattached as__cause__so the root cause is never swallowed.
Common Misconceptions
- Reading only the top line or a random middle line: Read the bottom exception summary first, then walk the exception chain and relevant call frames to locate the trigger.
- Sending screenshots of tracebacks: Always copy and paste plain text so teammates and AI tools can search symbols and line numbers directly.
- Raising a new exception without
from e: While Python automatically attaches implicit context ("During handling..."), writingraise NewError(...) from eexplicitly documents causal wrapping; usefrom Noneonly when you intentionally want to suppress noisy internal tracebacks. - Logging
print(e)instead of the full traceback: Printing only the exception message discards every file and line number. Uselogger.exception(...)in logging code (see k1.prog.logging).
Connection to AI Development
- Deep learning tracebacks are deep: PyTorch errors routinely pass through dozens of internal dispatcher frames. Look for the frame inside your own
forward()or training step alongside the final tensor shape or device mismatch message (e.g.,mat1 and mat2 shapes cannot be multiplied). - CUDA errors are reported asynchronously: Because GPU kernels execute asynchronously, a CUDA traceback may point to a later line of Python code. PyTorch docs recommend running with
CUDA_LAUNCH_BLOCKING=1when isolating the exact failing kernel call: https://docs.pytorch.org/docs/stable/notes/cuda.html - When pasting a stack trace to an AI assistant: Include the full traceback text, identify which frames belong to your project, and paste the surrounding source lines—after redacting any API keys, internal hostnames, or user PII that might appear in local variable dumps.
Further Reading
- Python Tutorial — Errors and Exceptions: https://docs.python.org/3/tutorial/errors.html
- Python
tracebackModule: https://docs.python.org/3/library/traceback.html - PEP 657 — Fine-Grained Error Locations in Tracebacks: https://peps.python.org/pep-0657/
- PEP 3134 — Exception Chaining and Embedded Tracebacks: https://peps.python.org/pep-3134/
Comprehension Check
When a traceback contains "The above exception was the direct cause of the following exception," should you inspect only the bottom exception?
Reference answer: No. Inspect the entire causal chain: the outer exception describes the high-level operation that failed, while the inner exception explains the specific low-level trigger.
Verification & Reproduction
Verified on: 2026-10-14. Example status: Passed. Run log: 15_stack_trace.py.
Companion Code & Verification Materials