Find a course

Module 5: Web Pages, Errors and Async CodeLesson 11 of 1212 min

Errors, Debugging and try...catch

Read error messages, recognize common error types, debug with console.log and breakpoints, and handle failures gracefully with try...catch.

Step 1 of 13Learn

Errors are messages, not insults

Every programmer, at every level, writes code that breaks. The difference between a beginner and an experienced developer is not how many errors they make but how fast they find them. That starts with reading the error message instead of panicking at the red text.

A typical message has three parts:

Uncaught TypeError: Cannot read properties of undefined (reading 'name') at app.js:14:22

  • The type of error: TypeError.
  • A description: something was undefined, and the code tried to read its name property.
  • The location: file app.js, line 14, column 22.

The most common types:

ErrorUsually meansExample
SyntaxErrorThe code isn't valid JavaScriptmissing ) or }, unclosed string
ReferenceErrorA name doesn't existtypo: consol.log, or using a variable outside its scope
TypeErrorA value is the wrong type for the operationcalling something that isn't a function, reading a property of null or undefined
RangeErrorA number is out of an allowed rangenew Array(-1), infinite recursion

A SyntaxError stops the whole script before anything runs. The others happen at runtime, when the faulty line is reached, so code before that line has already run.

Step 2 of 13Practice · Diagram

Reading an error message

Which part tells you where to start looking in your code?

Tap the shape that answers the question, then press Check.

Reading an error messageParts diagram: TypeError ... at app.js:14:22, Type: TypeError, Description, File: app.js, Line: 14, Column: 22.TypeError ...at app.js:14:22Type:TypeErrorDescriptionFile: app.jsLine: 14Column: 22
TypeError ... at app.js:14:22

Full message: Uncaught TypeError: Cannot read properties of undefined (reading 'name') at app.js:14:22

Type: TypeError

A value was the wrong kind for the operation.

Description

Something was undefined and the code tried to read its name property.

File: app.js

Click it in DevTools to jump straight to the code.

Line: 14

Start your investigation here.

Column: 22

The exact character on that line.

Step 3 of 13Practice · Match the pairs

Match each piece of code to the error it causes.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. consle.log("hi")
  2. const x = 5; x();
  3. console.log("hi"
  4. let user; user.name;
  5. new Array(-1)

Step 4 of 13Learn

A debugging method that works

Random changes rarely fix bugs. A systematic approach does:

  1. Reproduce the bug reliably. Which input, which click, which order of steps causes it?
  2. Read the error message and go to the line it names.
  3. Inspect the values. Add console.log calls to see what variables actually hold, not what you assume they hold: console.log("cart:", cart, "total:", total);. Labeling each value saves confusion.
  4. Narrow down. Find the last point where values are correct and the first point where they are wrong. The bug lives between them.
  5. Fix one thing, then test again.

Browser developer tools go further than logging. In the Sources tab you can click a line number to set a breakpoint. When execution reaches that line, the program pauses, and you can see every variable's current value and step through the code one line at a time. Writing the keyword debugger; in your code does the same when dev tools are open.

Other useful console methods: console.table(arrayOfObjects) prints data as a table, and console.error and console.warn print highlighted messages.

Explaining your code line by line, out loud or in writing, also works surprisingly often. Developers call it rubber duck debugging: describing what each line should do forces you to notice where it doesn't.

Step 5 of 13Practice · Put in order

Put these debugging steps in a sensible order.

Drag the items, or use the arrow buttons, to put them in order.

  1. Narrow down where correct values become wrong
  2. Read the error message and find the line
  3. Log or inspect the actual values of the variables involved
  4. Make one fix and test again
  5. Reproduce the bug with a specific input

Step 6 of 13Diagram

The debugging loop

The debugging loopCycle diagram: Reproduce → Read the error → Inspect values → Narrow down → Fix one thing, test.Repeat until fixedReproduceRead the errorInspect valuesNarrow downFix one thing,test

Tap a shape with to see more.

Reproduce

Find the exact input or clicks that cause the bug.

Read the error

Go to the line it names.

Inspect values

console.log or breakpoints: what do variables really hold?

Narrow down

Last correct point, first wrong point: the bug is between.

Fix one thing, test

One change at a time, so you know what worked.

Step 7 of 13Learn

Handling errors with try...catch

Some errors are not bugs in your code but problems with the outside world: a user types invalid data, a server is down, a file is malformed. You can't prevent them, but you can handle them so the program keeps working:

function parseSettings(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    console.warn("Bad settings, using defaults:", error.message);
    return { theme: "light" };
  }
}
  • Code in the try block runs normally.
  • If anything inside throws an error, execution jumps to catch, which receives the error object. error.name and error.message describe it.
  • An optional finally block runs either way, useful for cleanup such as hiding a loading spinner.

You can also throw your own errors when something is invalid:

function withdraw(balance, amount) {
  if (amount > balance) {
    throw new Error("Insufficient funds");
  }
  return balance - amount;
}

Use try...catch around code that can legitimately fail, such as parsing input or loading data. Don't wrap everything to hide errors; an empty catch {} that swallows mistakes makes bugs much harder to find later.

Step 8 of 13Note

Step 9 of 13Practice · Code challenge

Write a function safeParse(text) that returns the result of JSON.parse(text), or returns null if the text is not valid JSON.

Runs in a sandbox in your browser.
  • safeParse('{"a": 1}')
  • safeParse("not json")
  • safeParse("[1, 2]")

Step 10 of 13Note

Step 11 of 13Practice · Sort into groups

Should each problem be handled with try...catch, or fixed in the code?

Tap an item, then tap its group (or drag it there).

Step 12 of 13Tap to reveal

Reading a stack trace

  1. What it is

    When an error is thrown inside nested function calls, the console shows a stack trace: a list of the functions that were running, from the one where the error happened down to the one that started it all.

  2. Read from the top

    The first line names the error and the exact location. The lines below it show who called that function, and who called that one. Click a file name to jump straight to that line in the Sources panel.

  3. Find your own code

    Stack traces often pass through library code you did not write. Skip those lines and look for the first file that is yours; that is usually where the wrong value was passed in.

  4. Use it with logging

    Once you know the line, log the values that line uses. The combination of where (from the stack trace) and what (from your logs) solves most bugs in minutes instead of hours.

Step 13 of 13Practice · What would you do?

What would you do?

A teammate wraps a whole 200-line function in try { ... } catch (e) { } with an empty catch block "so users never see errors." What is the main problem?