SyntaxPilot
Courses/JavaScript/Lesson 13

JavaScript · Lesson 13 of 40 · 10 min

Errors and try/catch

queued

These are the notes for JavaScript episode 13. You will learn why one uncaught error stops the whole program, try and catch (the safety net), the error object (name, message, stack trace), why some mistakes give a silent wrong answer instead of an error, how to throw your own errors with new Error(...), finally (code that always runs, even after return), the built-in error types (ReferenceError, TypeError, RangeError, SyntaxError), catching only what you expect with instanceof and rethrowing the rest, and a mini project: a safe order checker. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js).

The stack traces below are shortened: ... stands for the folder your file is in and the lines from Node itself.

The problem: one bad order stops everything

Ravi's tea shop app prints three orders. Meena's order has no item:

const orders = [
  { customer: "Asha", item: "chai", qty: 3 },
  { customer: "Meena", qty: 2 },
  { customer: "Ravi", item: "samosa", qty: 1 },
];
for (const order of orders) {
  console.log(`${order.customer}: ${order.qty} x ${order.item.toUpperCase()}`);
}
console.log("All orders done!");
Asha: 3 x CHAI
.../main.js:7
  console.log(`${order.customer}: ${order.qty} x ${order.item.toUpperCase()}`);
                                                              ^

TypeError: Cannot read properties of undefined (reading 'toUpperCase')
    at Object.<anonymous> (main.js:7:63)
    ...

order.item is undefined for Meena, and undefined has no toUpperCase. The real damage is what's missing: Ravi's perfectly good order never printed, and neither did All orders done!.

Why it failed: when JavaScript hits an error that nothing handles (an uncaught error), it stops the program right there. We need a way to say "try this, and if it fails, don't die: do something else".

try and catch: the safety net

At the circus In JavaScript What it does
Walking the tightrope (the risky part) try { ... } the code that might fail
The net under the rope catch (err) { ... } runs only if something in try threw
Noting why the walker fell err.name, err.message what went wrong
const orders = [
  { customer: "Asha", item: "chai", qty: 3 },
  { customer: "Meena", qty: 2 },
  { customer: "Ravi", item: "samosa", qty: 1 },
];
for (const order of orders) {
  try {
    console.log(`${order.customer}: ${order.qty} x ${order.item.toUpperCase()}`);
  } catch (err) {
    console.log(`Skipped ${order.customer}: ${err.message}`);
  }
}
console.log("All orders done!");
Asha: 3 x CHAI
Skipped Meena: Cannot read properties of undefined (reading 'toUpperCase')
Ravi: 1 x SAMOSA
All orders done!
  • The try is inside the loop, so only one order fails and the loop moves on.
  • If nothing in try fails, catch is skipped completely.
  • err is just a name (like a function parameter); e and error are also common.

The error object, and where try stops

try {
  console.log("1. before");
  const bill = price * 2;
  console.log("2. never printed");
} catch (err) {
  console.log("3. caught:", err.name);
  console.log("4. message:", err.message);
}
console.log("5. the app keeps going");
1. before
3. caught: ReferenceError
4. message: price is not defined
5. the app keeps going

The moment an error happens, try stops at that line and jumps straight to catch. Line 2 never runs. Every error object has:

  • name: the kind of error (ReferenceError, TypeError, ...)
  • message: a human-readable description
  • stack: the stack trace, the list of function calls that led to the error (this is what Node prints for an uncaught error)

Silent wrong answers

Some mistakes don't crash at all:

function makeBill(item, qty, price) {
  return `${item}: ${qty} x ${price} = Rs ${qty * price}`;
}
console.log(makeBill("chai", 3, 10));
console.log(makeBill("chai", -2, 10));
console.log(makeBill("chai", "two", 10));
chai: 3 x 10 = Rs 30
chai: -2 x 10 = Rs -20
chai: two x 10 = Rs NaN

A bill of minus 20 rupees and a bill of NaN (Not a Number), with no error. JavaScript can't know that a quantity must be a positive whole number: that's a business rule of Ravi's shop. A silent wrong answer is worse than a crash, because nobody notices it.

throw: raise the alarm yourself

throw creates an error on purpose. It stops the function right there, exactly like a built-in error:

function makeBill(item, qty, price) {
  if (!Number.isInteger(qty) || qty <= 0) {
    throw new Error(`Bad quantity for ${item}: ${qty}`);
  }
  return `${item}: ${qty} x ${price} = Rs ${qty * price}`;
}
console.log(makeBill("chai", 3, 10));
console.log(makeBill("chai", -2, 10));
console.log("never printed");
chai: 3 x 10 = Rs 30
.../main.js:3
    throw new Error(`Bad quantity for ${item}: ${qty}`);
    ^

Error: Bad quantity for chai: -2
    at makeBill (main.js:3:11)
    at Object.<anonymous> (main.js:8:13)
    ...

Read the stack trace from the top: the error was thrown in makeBill (line 3), which was called from line 8. Thrown but not caught, so the program still stopped. Now catch it where you can handle it:

function makeBill(item, qty, price) {
  if (!Number.isInteger(qty) || qty <= 0) {
    throw new Error(`Bad quantity for ${item}: ${qty}`);
  }
  return `${item}: ${qty} x ${price} = Rs ${qty * price}`;
}
for (const qty of [3, -2, "two", 1]) {
  try {
    console.log(makeBill("chai", qty, 10));
  } catch (err) {
    console.log("Rejected:", err.message);
  }
}
chai: 3 x 10 = Rs 30
Rejected: Bad quantity for chai: -2
Rejected: Bad quantity for chai: two
chai: 1 x 10 = Rs 10

Rule of thumb: throw where you find the problem, catch where you can handle it.

finally: code that always runs

Ravi opens the counter for each customer, and it must close whether serving worked or failed. Writing "close" in both try and catch is copy-paste, and a return inside try would skip code after it anyway. finally runs after try and catch, every time:

function serve(customer, qty) {
  console.log(`Open counter for ${customer}`);
  try {
    if (qty > 5) throw new Error("Not enough chai");
    return `${qty} chai for ${customer}`;
  } catch (err) {
    return `Sorry ${customer}: ${err.message}`;
  } finally {
    console.log("Close counter");
  }
}
console.log(serve("Asha", 2));
console.log(serve("Meena", 9));
Open counter for Asha
Close counter
2 chai for Asha
Open counter for Meena
Close counter
Sorry Meena: Not enough chai

Close counter prints before the returned text: try said return, but finally ran first, before the function actually left. Typical uses: closing files and connections, hiding a loading spinner, releasing a lock.

Error types

const tests = [
  () => totl + 1,
  () => (5).toUpperCase(),
  () => new Array(-1),
  () => { throw new Error("Out of milk"); },
];
for (const test of tests) {
  try {
    test();
  } catch (err) {
    console.log(`${err.name}: ${err.message}`);
  }
}
ReferenceError: totl is not defined
TypeError: 5.toUpperCase is not a function
RangeError: Invalid array length
Error: Out of milk
Type When Example
ReferenceError a name that doesn't exist (often a typo) totl + 1
TypeError a value used in a way its type can't support undefined.trim(), (5).toUpperCase()
RangeError a value outside the allowed range new Array(-1)
SyntaxError the code breaks the language's grammar; found before anything runs try { } with no catch
Error the general type; what you usually throw yourself throw new Error("Out of milk")

Catch what you expect, rethrow the rest

A catch that swallows every error also hides real bugs. Check the type with instanceof and throw anything unexpected again (rethrowing):

const menu = { chai: 10, samosa: 12 };
function getPrice(menu, item) {
  if (!(item in menu)) throw new RangeError(`No price for ${item}`);
  return menu[item];
}
function order(menu, item) {
  try {
    return getPrice(menu, item);
  } catch (err) {
    if (err instanceof RangeError) {
      console.log("Not on the menu:", item);
      return 0;
    }
    throw err;
  }
}
console.log(order(menu, "chai"));
console.log(order(menu, "pizza"));
console.log(order(undefined, "chai"));
10
Not on the menu: pizza
0
.../main.js:14
    throw err;
    ^

TypeError: Cannot use 'in' operator to search for 'chai' in undefined

The customer's mistake (pizza) is handled. Our own bug (forgetting to pass the menu) crashes loudly, which is exactly what you want while developing. x instanceof RangeError is true when x was made by RangeError (more on instanceof with classes in episode 16).

Common mistakes (and what really happens)

You wrote What happens Why Fix
try { ... } with nothing after SyntaxError: Missing catch or finally after try try needs a catch or a finally add catch (err) { ... }
throw "Out of milk"; (no error) err.message is undefined, no stack trace a string isn't an Error throw new Error("Out of milk")
catch (err) {} (no error) real bugs silently hidden swallows every error handle it, or throw err
try { const total = 30; } ... console.log(total); ReferenceError: total is not defined let/const live only inside the block declare let total; before try
makeBill("chai", -2, 10) (no error) Rs -20 JavaScript can't know your rules check and throw
order.item.toUpperCase() with no item TypeError: Cannot read properties of undefined (reading 'toUpperCase') undefined has no methods check first, or try/catch

The two "no catch" and "string" cases, run for real:

try {
  throw "Out of milk";
} catch (err) {
  console.log(err, "|", err.message);
}
try {
  throw new Error("Out of milk");
} catch (err) {
  console.log(err.message);
}
Out of milk | undefined
Out of milk
try {
  console.log("risky work");
}
console.log("after");
.../main.js:3
}
^

SyntaxError: Missing catch or finally after try

Because it's a SyntaxError, nothing runs, not even risky work. try/catch can't catch grammar mistakes in the same file.

Mini project: a safe order checker

const menu = { chai: 10, samosa: 12, jalebi: 30 };
function checkOrder({ customer, item, qty }) {
  if (!item) throw new Error("no item");
  if (!(item in menu)) throw new Error(`${item} is not on the menu`);
  if (!Number.isInteger(qty) || qty <= 0) throw new Error(`bad quantity ${qty}`);
  return qty * menu[item];
}
const orders = [
  { customer: "Asha", item: "chai", qty: 3 },
  { customer: "Meena", qty: 2 },
  { customer: "Ravi", item: "pizza", qty: 1 },
  { customer: "Kiran", item: "jalebi", qty: -1 },
  { customer: "Sonu", item: "samosa", qty: 2 },
];
let total = 0, failed = 0;
for (const o of orders) {
  try {
    const bill = checkOrder(o);
    total += bill;
    console.log(`OK   ${o.customer}: Rs ${bill}`);
  } catch (err) {
    failed++;
    console.log(`FAIL ${o.customer}: ${err.message}`);
  }
}
console.log(`Total Rs ${total}, ${failed} orders failed`);
OK   Asha: Rs 30
FAIL Meena: no item
FAIL Ravi: pizza is not on the menu
FAIL Kiran: bad quantity -1
OK   Sonu: Rs 24
Total Rs 54, 3 orders failed
  • checkOrder validates (checks the rules) and throws with a clear reason; it uses parameter destructuring from episode 12.
  • The loop catches each failure, counts it, and moves on. Nothing crashes, and every bad order says why.

Try adding a rule: no more than 10 of one item.

Practice

  1. Write safeDivide(a, b) that throws when b is 0, and catch it.
  2. Add a "maximum 10" rule to a quantity check, throwing a RangeError.
  3. Use finally to print order closed after every order.
Solutions and hints
function safeDivide(a, b) {
  if (b === 0) throw new Error("Cannot divide by zero");
  return a / b;
}
for (const [a, b] of [[10, 2], [5, 0]]) {
  try {
    console.log(`${a} / ${b} = ${safeDivide(a, b)}`);
  } catch (err) {
    console.log("Error:", err.message);
  }
}
function checkQty(qty) {
  if (!Number.isInteger(qty) || qty <= 0) throw new Error(`bad quantity ${qty}`);
  if (qty > 10) throw new RangeError(`max 10 per order, got ${qty}`);
  return qty;
}
for (const qty of [3, 12, 0]) {
  try {
    console.log("ok", checkQty(qty));
  } catch (err) {
    console.log(`${err.name}: ${err.message}`);
  } finally {
    console.log("order closed");
  }
}
10 / 2 = 5
Error: Cannot divide by zero
ok 3
order closed
RangeError: max 10 per order, got 12
order closed
Error: bad quantity 0
order closed
  1. Without the check, 5 / 0 is Infinity in JavaScript, another silent surprise.
  2. err.name tells the two kinds of failure apart.
  3. finally runs after both the success and the failure paths.

Quick quiz

What does this print?

try {
  console.log("A");
  throw new Error("B");
  console.log("C");
} catch (e) {
  console.log(e.message);
} finally {
  console.log("D");
}
  • A. A C D
  • B. A B D
  • C. A B C D
  • D. A D
Answer

B. throw jumps straight to catch, so C never prints. catch prints the message B, and finally always prints D.

Interview questions

  • What happens to a Node.js program when an error isn't caught?
  • How do try, catch and finally work together? When does finally run?
  • If try contains a return, does finally still run? In what order?
  • What's the difference between ReferenceError, TypeError, RangeError and SyntaxError?
  • Why can't try/catch catch a SyntaxError in the same file?
  • Why should you throw new Error(...) rather than throw a string?
  • What is a stack trace and how do you read it?
  • Why is an empty catch block dangerous? What is rethrowing?
  • Where should you throw an error, and where should you catch it?

Glossary

Term Meaning Example
Error (exception) an object describing something that went wrong; it stops normal flow new Error("Out of milk")
Uncaught error an error nothing handles; it stops the program the crash in the first example
try the block of code that might fail try { risky(); }
catch the block that runs only if try threw; receives the error catch (err) { ... }
finally the block that always runs after try/catch, even after return finally { close(); }
throw raise an error on purpose throw new Error("bad qty")
err.name the kind of error "TypeError"
err.message the description of the error "price is not defined"
Stack trace the chain of function calls that led to an error at makeBill (main.js:3:11)
Validation checking that a value follows your rules before using it if (qty <= 0) throw ...
Business rule a rule of your app the language can't know "a quantity is a positive whole number"
ReferenceError using a name that doesn't exist totl is not defined
TypeError using a value in a way its type can't support Cannot read properties of undefined
RangeError a value outside the allowed range Invalid array length
SyntaxError code that breaks the grammar; nothing runs Missing catch or finally after try
instanceof checks which kind (constructor) made an object err instanceof RangeError
Rethrow throwing a caught error again because you can't handle it throw err;
NaN "Not a Number", the result of failed number maths "two" * 10

Summary

  • An uncaught error stops the whole program, including all the good work after it.
  • try { } catch (err) { } is the safety net: try stops at the failing line and jumps to catch. Put it where one failure should not stop the rest (often inside a loop).
  • err.name, err.message and the stack trace tell you what went wrong and where.
  • Some mistakes are silent (Rs -20, NaN). Check your rules and throw new Error("...").
  • finally always runs, even after return: use it for cleanup.
  • Catch what you expect (instanceof), and rethrow the rest so real bugs stay loud.

Next episode: reading input from stdin in Node.js. Every order so far was written inside the code; next, the user types them, and today's try/catch will come in handy.