TExcelTAD
Home › JavaScript › JS Errors

JavaScript Errors

Things go wrong: input is invalid, a network request fails, a property is read from undefined. When JavaScript hits a problem it throws an error, which stops normal execution. With try…catch you can catch the error, react to it, and keep your program running.

try…catch

Code that might fail goes in the try block. If anything in it throws, execution jumps straight to catch, which receives the error object:

js · try it yourself
console.log("before");
try {
  const user = undefined;
  console.log(user.name);          // throws a TypeError
  console.log("never reached");
} catch (err) {
  console.log("Caught:", err.name);
  console.log("Message:", err.message);
}
console.log("after — the program keeps running");
before
Caught: TypeError
Message: Cannot read properties of undefined (reading 'name')
after — the program keeps running

Every error object has a name (its type) and a message (a human-readable description). It usually also has a stack property showing where it happened — useful for debugging, but it differs between environments.

Built-in error types

Type Thrown when… Example
ReferenceError using a variable that doesn't exist notDeclared + 1
TypeError a value is the wrong type for the operation null.length, 5()
SyntaxError code or data can't be parsed JSON.parse("{bad}")
RangeError a number is outside the allowed range new Array(-1)
URIError bad URI encoding decodeURIComponent("%")
js · try it yourself
const attempts = [
  () => notDeclared + 1,
  () => (5)(),
  () => JSON.parse("{bad json}"),
  () => (12.5).toFixed(200),
];
for (const attempt of attempts) {
  try {
    attempt();
  } catch (err) {
    console.log(`${err.name}: ${err.message}`);
  }
}
ReferenceError: notDeclared is not defined
TypeError: 5 is not a function
SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
RangeError: toFixed() digits argument must be between 0 and 100

(Exact messages vary slightly between browsers; the name is always the same.)

Throwing your own errors

Use throw to signal that something is wrong. Always throw an Error object (or a subclass), not a plain string, so callers get a message and a stack trace:

js · try it yourself
function withdraw(balance, amount) {
  if (typeof amount !== "number" || Number.isNaN(amount)) {
    throw new TypeError("Amount must be a number");
  }
  if (amount <= 0) {
    throw new RangeError("Amount must be positive");
  }
  if (amount > balance) {
    throw new Error(`Insufficient funds: balance is ${balance}`);
  }
  return balance - amount;
}

for (const amount of [30, -5, 500, "ten"]) {
  try {
    console.log("New balance:", withdraw(100, amount));
  } catch (err) {
    console.log(`${err.name}: ${err.message}`);
  }
}
New balance: 70
RangeError: Amount must be positive
Error: Insufficient funds: balance is 100
TypeError: Amount must be a number

finally

A finally block runs no matter what — after try succeeds, after catch handles an error, even after a return. It's the place for clean-up work like closing files or hiding a loading spinner:

js · try it yourself
function load(ok) {
  console.log("show spinner");
  try {
    if (!ok) throw new Error("network down");
    return "data loaded";
  } catch (err) {
    return "failed: " + err.message;
  } finally {
    console.log("hide spinner");
  }
}
console.log(load(true));
console.log(load(false));
show spinner
hide spinner
data loaded
show spinner
hide spinner
failed: network down

Custom error classes

Extend Error to create your own error types. Then instanceof lets you handle different failures differently and re-throw the ones you don't know how to handle:

js · try it yourself
class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

function register(user) {
  if (!user.email?.includes("@")) {
    throw new ValidationError("email", "Please enter a valid email");
  }
  return "registered " + user.email;
}

for (const u of [{ email: "zoe@example.com" }, { email: "zoe" }]) {
  try {
    console.log(register(u));
  } catch (err) {
    if (err instanceof ValidationError) {
      console.log(`Field "${err.field}": ${err.message}`);
    } else {
      throw err;   // unexpected — let it propagate
    }
  }
}
registered zoe@example.com
Field "email": Please enter a valid email

Since ES2022 you can also attach the original error as a cause: throw new Error("Saving failed", { cause: err }).

Tip: Don't wrap everything in try…catch. Catch errors where you can actually do something useful — show a message, retry, use a fallback — and let the rest propagate.

Test yourself

When does a finally block run?

  1. Only if no error occurred
  2. Only if an error was caught
  3. Always, after try/catch
  4. Only when there is no catch block

Which error type is thrown by null.length?

  1. ReferenceError
  2. TypeError
  3. RangeError
  4. SyntaxError

What is the best thing to throw?

  1. A string
  2. A number
  3. An Error object (or subclass)
  4. null