Course outline · 0% complete

0/29 lessons0%

Course overview →

Errors, throw, and try/catch

lesson 8-3 · ~11 min · 27/29

Reading an error like a pro

Every JavaScript error message has the same anatomy, and reading it calmly is half of debugging:

TypeError: Cannot read properties of undefined (reading 'name')
    at main.js:3
  • The name (TypeError) says what category went wrong.
  • The message says exactly what happened: something was undefined and you asked for its .name.
  • The stack trace lines point at the file and line number. Start at the top one.

The three you will meet most:

ErrorUsual meaning
ReferenceError: x is not definedtypo in a name, or the variable is out of scope (lesson 6-3)
TypeError: ... of undefineda lookup returned undefined and you kept going
SyntaxErrorthe code itself is malformed, often a missing brace or quote
TypeError: Cannot read properties ofundefined (reading 'name') at main.js:3error namewhat happenedfile and line numberread name → message → location, in that order, before touching any code
The anatomy of a JavaScript error: category, explanation, and the exact line to look at.

throw and try/catch

Your own code can refuse bad input by throwing an error, and callers can recover with try/catch. This is Python's raise and try/except mechanism with different keywords — raise becomes throw, except becomes catch — and the control flow is identical:

function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }
  return a / b;
}

A throw stops the function on the spot. If nothing catches it, the whole program crashes with the message you wrote. A try block volunteers to handle trouble: when anything inside throws, execution jumps straight to catch, receives the error object, and the program lives on. err.message holds the text you passed to new Error(...).

Code exercise · javascript

Run it. The second divide call throws, so the line after it inside try never runs. catch receives the error and the program continues normally.

Code exercise · javascript

Your turn. JSON.parse (lesson 5-3) throws on malformed text. Wrap the parse in try/catch: on success print the parsed object's name, on failure print Invalid JSON.

Code exercise · javascript

Second practice. Write checkAge(age) that throws new Error("Invalid age") when age is NaN or negative, and returns it otherwise. The try block calls it with Number("twenty") — which is NaN (lesson 8-2) — so catch should fire. The program must print Invalid age, then Still running.

Quiz

Your program prints: ReferenceError: userName is not defined. What is the most likely cause?