Skip to content

Lesson 14 of 18Working like an engineer

Reading Errors and Debugging Anything

Read Python tracebacks and JavaScript stack traces, find your own line among library frames, and debug any problem with a repeatable method.

19 min read0/5 questions

Your machine is set up and your tools are ready. This last unit is about the habits that make you useful on a team, starting with the one you will use daily. Every engineer, from first week to staff level, spends part of every day looking at errors. The difference between a junior who loses an afternoon and a senior who fixes it in five minutes is rarely cleverness. It is that the senior actually reads the error, knows which line of it matters, and has a calm routine for the cases where the error does not explain itself. In "How to learn well" you met a short debugging routine. This lesson turns it into a real skill: you will run code that crashes, read the output line by line in Python and JavaScript, and learn the method professionals use on bugs that have no error at all.

The four parts of every error

Run this. It prints one label and then crashes. That is the point.

Python
users = [ {"name": "Ada", "address": {"city": "London"}}, {"name": "Grace"},] def get_city(user): return user["address"]["city"] def shipping_label(user): return f"{user['name']}, {get_city(user)}" def print_labels(users): for user in users: print(shipping_label(user)) print_labels(users)
Output
Press Run (⌘ Enter) to see what happens.

The red text looks like noise at first, but it always has the same four parts:

  1. The type: KeyError. This is the category of problem. Python has a few dozen built-in types and you will meet the same ten constantly: KeyError, IndexError, TypeError, ValueError, AttributeError, NameError, ImportError, ModuleNotFoundError, FileNotFoundError, ZeroDivisionError.
  2. The message: 'address'. The detail. For a KeyError the message is the missing key. For other types it is a sentence.
  3. The location: File "main.py", line 7, in get_city. The exact file, line and function where it blew up.
  4. The stack trace: the list of function calls that led there. print_labels called shipping_label, which called get_city.

Read the type and message first. Together they are often enough: "a dictionary did not have the key address". Then the location tells you where, and the trace tells you how you got there.

Since Python 3.11, tracebacks also print ^^^^ markers under the exact part of the line that failed. On line 7 they point at user["address"], not at ["city"]. That matters when one line does several things.

Reading a Python traceback from the bottom up

Python prints the header Traceback (most recent call last). Take that literally: the last frame printed is the one where the error happened, and the first is where the program started. So you read Python tracebacks from the bottom up.

The call stack when the KeyError happened
  1. get_city(user)line 7: user['address'] fails
  2. shipping_label(user)line 10: called get_city
  3. print_labels(users)line 14: called shipping_label
  4. <module>line 16: the top level of main.py

Execution starts at the top level of the file, shown as <module>. Line 16 calls print_labels. This is the first frame Python prints.

1/5

That last step is the habit that separates good debuggers. The bottom frame tells you where the program noticed the problem. The cause can be higher up, or not in the stack at all: in this case it is the data. Grace was created without an address. The fix might be user.get("address", {}).get("city", "unknown"), or it might be rejecting users without an address when they are created. Reading the trace tells you where to look. Deciding the fix is still your job.

Predict the outputPython

What does this print?

data = {"user": {"name": "Ada"}}
try:
  print(data["user"]["email"])
except Exception as e:
  print(type(e).__name__, e)
Need a nudge? Hints walk you through it.

The same bug in JavaScript, read top down

Here is the identical program in JavaScript. The site only shows the first line of an uncaught error, so this version catches it and prints the full err.stack.

JavaScript
const users = [ { name: "Ada", address: { city: "London" } }, { name: "Grace" },]; function getCity(user) { return user.address.city;} function shippingLabel(user) { return `${user.name}, ${getCity(user)}`;} function printLabels(users) { for (const user of users) { console.log(shippingLabel(user)); }} try { printLabels(users);} catch (err) { console.log(err.stack);}
Output
Press Run (⌘ Enter) to see what happens.

Two things are different. First, the message. JavaScript does not complain about the missing address. Reading a missing property just gives undefined, silently. The crash comes one step later, when you try to read city from undefined. Chrome and Node say Cannot read properties of undefined (reading 'city'). Firefox and Safari word it differently. So in JavaScript, "cannot read X of undefined" means "the thing before .X was missing". Look one step to the left.

Second, the order. JavaScript, Java, C# and Go print the most recent call first. You read them top down. Here is the same error from Node on a real machine:

TypeError: Cannot read properties of undefined (reading 'city')
    at getCity (/app/labels.js:7:23)
    at shippingLabel (/app/labels.js:11:27)
    at printLabels (/app/labels.js:16:17)
    at Object.<anonymous> (/app/labels.js:21:3)
    at Module._compile (node:internal/modules/cjs/loader:1804:14)
    at Module.load (node:internal/modules/cjs/loader:1525:32)
    at Module._load (node:internal/modules/cjs/loader:1327:12)

Each line is at functionName (file:line:column). The first at line is where it broke. In the browser block above, the locations look strange (something like <anonymous>:9:22) because the site runs your code inside a wrapper function, so line numbers can be off by a line or two. The function names are still right, and the function names are what you navigate by.

The rule that covers both languages: find the line that says what went wrong, then find the nearest frame in a file you wrote.

Predict the outputJavaScript

What does this print?

const user = { name: "Grace" };
console.log(`${user.name}, ${user.address?.city}`);
Need a nudge? Hints walk you through it.

Finding your frame among library frames

Real tracebacks are long because your code calls libraries, and libraries call other libraries. Most of the frames are not yours, and the bug is almost never in them. Run this config loader:

Python
import json class ConfigError(Exception): pass def load_config(text): try: return json.loads(text) except json.JSONDecodeError as err: raise ConfigError("settings file is not valid JSON") from err raw = '{"port": 8000, "debug": true,}'load_config(raw)
Output
Press Run (⌘ Enter) to see what happens.

This output has two tracebacks joined by a sentence. Read it in pieces:

  • The bottom traceback ends with ConfigError: settings file is not valid JSON. That is the error the program finally died with.
  • The sentence The above exception was the direct cause of the following exception means someone wrote raise ... from err. The upper traceback is the original problem.
  • The upper traceback has frames in json/__init__.py and json/decoder.py. Those are the standard library, not you. Skip them. The one frame in main.py is load_config, line 8.
  • Its last line is the real clue: a JSONDecodeError with a line and column. Column 29 is the trailing comma after true. JSON does not allow it.

There is a second joining sentence you will see: During handling of the above exception, another exception occurred. That one means a new bug happened inside an except block while handling the first. A common case is a typo in error-handling code, which nobody tested because errors are rare. When you see this sentence, you have two bugs to fix.

In JavaScript the equivalent is the cause property (new Error("bad config", { cause: err })), and Node prints it after a [cause]: label. Java prints Caused by:. Same idea everywhere: the last error is the symptom, the cause is underneath.

Quick check
A traceback shows a KeyError, then 'During handling of the above exception, another exception occurred', then an AttributeError. What happened?
Need a nudge? A hint rules out a wrong answer.

Syntax, runtime and logic errors

Errors come in three families, and each one is found differently.

Syntax errors mean the code is not valid in the language at all, so nothing runs. Run this and notice there is no Traceback header, only a location and a caret:

Python
total = 42print("total:" total)
Output
Press Run (⌘ Enter) to see what happens.

Python even guesses the fix: Perhaps you forgot a comma?. Syntax errors are the easiest family because the tool tells you exactly where. One catch: sometimes the real mistake is a line above the reported one, such as a bracket that was never closed. If the reported line looks fine, look up.

Runtime errors happen while the program runs, only on the path that triggers them. Everything in the sections above was a runtime error. Ada's label printed fine. Grace's crashed. Code can run for months before the input that breaks it shows up.

Logic errors are the hardest: no error at all, just the wrong result. Grace, undefined is one. So is adding tax twice, or an off-by-one loop that skips the last item. No traceback will help you here. You need the method later in this lesson, and tests that check results, not just that code runs.

Errors you will meet in your first month

Not every error comes from your code. Many come from the terminal, your environment or the network. These are worth recognising on sight:

You seeWhat it almost always meansFirst thing to check
command not found (exit code 127)The program is not installed, or not on your PATHIs it installed? Did you open a new terminal after installing?
Permission deniedYour user may not read, write or run that file or portFile permissions (or, on Linux, a port below 1024). Do not reach for sudo first
EADDRINUSE / "address already in use"Another process already listens on that portAn old dev server you forgot. Stop it, or use another port
ModuleNotFoundError / Cannot find moduleThe package is not installed in the environment that is runningIs the virtual environment active? Did you run npm install?
CORS policy in the browser consoleThe API did not allow your page's originThe fix is a header on the server
401Not authenticated: missing or expired login or tokenIs the token sent? Has it expired?
403Authenticated, but not allowedPermissions or roles, not your password
404Nothing at that URLTypos in the path, wrong base URL, wrong HTTP method
500The server crashedThe server's logs, not the browser

The ModuleNotFoundError row deserves a warning. When a package "is installed but Python cannot find it", the cause is nearly always two Pythons: you installed into one and ran the other. python3 -m pip install and uv run avoid this by tying the install to a specific interpreter.

Match the pairs0/6 matched

Match each message to its most likely cause.

Choose an item, then its match on the other side.

A method for bugs that do not explain themselves

When the error does not point at the cause, or there is no error, stop guessing and work like a scientist:

  1. Reproduce it reliably. Write down the exact steps, input and environment. A bug you cannot trigger on demand is a bug you cannot prove you fixed.
  2. Shrink it. Remove everything that is not needed to trigger it. Delete code, use smaller input, hard-code values. The result is a minimal reproducible example (MRE). Very often you find the bug while shrinking, because the moment it disappears you know the last thing you removed was involved.
  3. Form one hypothesis. "The price is a string, not a number." Specific and testable.
  4. Change one thing, then run. If you change three things and it works, you do not know which one fixed it, or whether the other two broke something else.
  5. Verify, then add a test. Confirm the fix with the original steps, then write a test that would have caught it so it cannot come back.

Two cheap tricks help at step 3. Print the actual values: print(repr(price), type(price)) settles arguments about what a variable holds. And rubber duck debugging: explain the code line by line, out loud, to anyone or anything. You will often hear yourself say "and then this is definitely a number" and realise you never checked.

When something worked last week and is broken now, Git can search for you. git bisect checks out commits halfway between a good one and a bad one until it finds the exact commit that introduced the bug. You only have to say "good" or "bad" each time.

For Python's debugger tools (breakpoint(), pdb and post-mortem debugging), see "Debugging Python" in the Python Backend course. For puzzle-style stuckness on algorithm problems, see "Getting Unstuck".

Put it in order5 steps

A checkout total is sometimes wrong and there is no error. Put the steps in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Searching for an error well

Pasting your whole error into a search engine usually returns nothing, because it contains your file paths, user IDs and timestamps that nobody else has. Instead:

  • Copy the stable part. Cannot read properties of undefined (reading is stable. /Users/sam/code/shop/src/cart.js:41:7 is yours alone.
  • Add the tool and version. "pydantic 2 ValidationError field required" is far better than "field required".
  • Check the project first. Search the library's GitHub issues, and read its changelog if the error started after an upgrade. Someone may have reported it last week, with a workaround.
  • Check the date. A 2016 answer for a library that has had three major versions since may be wrong today.

AI assistants are good at errors, if you give them the full traceback, the code it points at and your versions. Then treat the answer as a hypothesis, not a fact: run it, and make sure you understand why it works. "Trust but Verify" in the AI Engineering course covers this habit.

Asking for help

Getting stuck is normal. Staying stuck silently for two days is the actual mistake. A good rule for juniors: try on your own for 30 to 60 minutes with the method above, then ask. Before asking, write the question so the other person can help in one reply:

  • What you are trying to do, in one sentence.
  • What you expected, and what actually happened (paste the full error as text, not a screenshot).
  • The smallest code that shows it, and the exact steps.
  • What you already tried, and what you ruled out.
  • Versions: language, key libraries, operating system.

Writing this often solves the problem before you send it. That is rubber ducking again, and it is why seniors ask for this format.

Key terms
stack trace
The list of function calls that were in progress when an error happened. Python prints it oldest first, JavaScript newest first.
frame
One entry in a stack trace: one function call, with its file and line number.
exception chaining
One error wrapping another. Python shows it with 'direct cause' (raise from) or 'During handling of the above exception'.
runtime error
An error raised while the program runs, only on the code path that triggers it.
logic error
A bug that produces a wrong result without any error message.
minimal reproducible example
The smallest code and input that still show the bug. Building one often reveals the cause.
git bisect
A Git command that binary-searches your history to find the commit that introduced a bug.