Reading stack traces

RoadmapsPython

Overview

A stack trace is a detailed error report that Python prints when your code crashes. It shows the exact path the code took before it failed. Imagine tracking a package delivery. The history shows exactly which cities the package passed through before it got lost. A stack trace shows exactly which functions your code called before the error happened. ```python def divide(a, b): return a / b def calculate_marks(total): # The error actually happens inside divide(), # but we called it from here. return divide(total, 0) calculate_marks(100) ``` The rule is: **read a stack trace from the bottom up.** The very last line tells you the exact error (e.g., `ZeroDivisionError`). The lines immediately above it tell you exactly which file and line number caused it.

It tells you exactly where to look to fix a crash. Without a stack trace, you would have to guess which function failed.

Where used: All Python code, Web servers, Data pipelines

Why learn this

Code walkthrough

def func_a():
    return func_b()

def func_b():
    print('Trace shows: func_a called func_b')
    print('Error happens here')

func_a()

Focus: print('Error happens here')

Aha moment

def a(): b()
def b(): c()
def c(): print('Crash!')

a()

Prediction: If `c()` crashes, will the stack trace mention `a()`?

Common guess: No, because the crash is in c().

The stack trace shows the full path. It will show `a()` called `b()`, and `b()` called `c()`. This helps you trace the origin of the bad data.

Common mistakes

Recall questions

Understanding checks

A stack trace shows an error happening inside `fastapi/routing.py`. Should you go edit `fastapi/routing.py` to fix the bug?

No. You should look slightly higher in the stack trace for a file that YOU wrote. You probably passed bad data to FastAPI.

Read a stack trace from the bottom up. The error often happens inside a library because your code gave it invalid data. Fix your code, not the library.

Your code crashes and prints 50 lines of error text. A classmate says, 'This is a huge error, your whole app is broken.' Is this true?

No. A long stack trace just means the code passed through many functions before the single failure occurred.

The length of the stack trace only shows how deeply nested the function calls were. It does not mean the error is hard to fix.

Practice tasks

Simulate tracing up

Given this code, change the final print statement to state the name of the function that originally started the chain.

Challenge

Trigger an error chain

Write two functions. `first()` should call `second()`. `second()` should trigger a `ZeroDivisionError` by dividing 1 by 0. Call `first()`.

Continue learning

Previous: try/except with specific exception types

Previous: Defining functions and return values

Return to Python Roadmap