Skip to content
Kuza Ndoto Academy

Error Handling

Beginner → IntermediateChapter 6 · Page 28 of 325 min readUpdated 15 Nov 2026

Things go wrong in every real program: a network request fails, a user types letters where you expected a number, saved data turns out to be corrupt. When JavaScript hits an error it stops the current code. try, catch and finally let you catch errors, recover gracefully and give the user a helpful message instead of a broken page.

What an error looks like

An uncaught error stops the script at that line and prints a red message in the console, like this one from trying to read a property of null:

const user = null;
console.log(user.name);
console.log("This line never runs");
Uncaught TypeError: Cannot read properties of null (reading 'name')

The exact wording differs between browsers (Firefox says "user is null"), but the type, TypeError, is the same everywhere. Every error is an object with a name, a message and a stack (the chain of function calls that led to it). The built-in types you will meet most are:

TypeMeaningExample cause
ReferenceErrorA variable that doesn't existconsole.log(totl) (typo)
TypeErrorA value used in a way its type doesn't allownull.name, calling something that isn't a function
SyntaxErrorCode or data that can't be parsedA missing bracket, JSON.parse("{bad}")
RangeErrorA number outside the allowed rangenew Array(-1), (5).toFixed(200)

A SyntaxError in your own code is special: the browser finds it before running anything, so the whole script fails to start. try/catch can only catch errors that happen while code is running.

try and catch

Put risky code in a try block. If anything inside throws, JavaScript jumps straight to the catch block and hands it the error object. After the catch finishes, the program carries on normally.

try {
  const user = null;
  console.log(user.name);
  console.log("skipped");
} catch (error) {
  console.log("Something went wrong:", error.name);
}
console.log("The program continues");
Something went wrong: TypeError The program continues

If you don't need the error object, you can leave out the brackets: catch { ... }.

Throwing your own errors

Use throw when your code detects a problem it can't handle itself. Always throw an Error object (or one of its subtypes), not a plain string, so the catcher gets a message and a stack trace.

function withdraw(balance, amount) {
  if (typeof amount !== "number" || Number.isNaN(amount)) {
    throw new TypeError("Amount must be a number");
  }
  if (amount > balance) {
    throw new RangeError(`Cannot withdraw KES ${amount}; balance is KES ${balance}`);
  }
  return balance - amount;
}

try {
  console.log(withdraw(1000, 300));
  console.log(withdraw(1000, 5000));
  console.log(withdraw(1000, 100));
} catch (error) {
  console.log(`${error.name}: ${error.message}`);
} finally {
  console.log("Transaction closed");
}
700 RangeError: Cannot withdraw KES 5000; balance is KES 1000 Transaction closed

The third withdraw never runs: the error from the second jumps straight to catch.

finally

A finally block runs no matter what: after try succeeds, after catch handles an error, and even if try contains a return. Use it for clean-up such as hiding a loading spinner or re-enabling a button.

function test() {
  try {
    return "from try";
  } finally {
    console.log("finally runs first");
  }
}
console.log(test());
finally runs first from try

Handling different errors differently

Use instanceof to check what kind of error you caught. Handle the ones you expect, and re-throw anything else so real bugs aren't hidden. You can create your own error types with classes:

class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

function checkPhone(phone) {
  if (phone.length !== 10) {
    throw new ValidationError("phone", "Phone number must have 10 digits");
  }
  return true;
}

try {
  checkPhone("07123");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name, "on", error.field + ":", error.message);
  } else {
    throw error;      // not ours to handle
  }
}
ValidationError on phone: Phone number must have 10 digits

When you catch one error and throw a clearer one, keep the original as the cause (supported in all modern browsers):

try {
  try {
    JSON.parse("{bad json}");
  } catch (err) {
    throw new Error("Could not read your saved settings", { cause: err });
  }
} catch (error) {
  console.log(error.message);
  console.log("Caused by:", error.cause.name);
}
Could not read your saved settings Caused by: SyntaxError

Errors in asynchronous code

A try/catch only covers code that runs while the try block is running. A callback that runs later is outside it:

try {
  setTimeout(() => {
    throw new Error("Too late!");
  }, 100);
} catch (error) {
  console.log("Caught?");      // never runs
}

By the time the timer fires, the try block finished long ago, so the error is uncaught. With promises, use .catch(); with async/await, put the await inside try, and a rejected promise is caught just like a normal error:

async function loadProfile() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const profile = await response.json();
    console.log(profile.name);
  } catch (error) {
    console.log("Could not load profile:", error.message);
  }
}
Common mistake

An empty catch {} that swallows errors silently. The program keeps going in a broken state and you have no clue why. At the very least log the error with console.error(error), and tell the user something useful ("Couldn't save. Check your connection and try again.").

Tip

Don't wrap everything in try/catch. Use it around operations that can fail for reasons outside your control: network requests, parsing outside data, storage and user input. A bug in your own logic is better fixed than caught.

Key points

  • Errors are objects with name, message and stack; common types are TypeError, ReferenceError, SyntaxError and RangeError.
  • try runs risky code, catch handles any error thrown, and finally always runs.
  • throw new Error("...") (or a subclass) signals problems; check types with instanceof and re-throw what you can't handle.
  • For async code use .catch() or await inside try; a callback that runs later isn't covered by an outer try.
Up next · Modern JavaScriptModulesimport and export to organise code.
→

Tip: use the ← and → keys to move between pages.