Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 156 ยท Errors and Debugging

Errors and try...catch

Learn what JavaScript errors are, read the built-in error types, handle problems with try, catch and finally, and inspect the error object safely.

Every program eventually meets a situation it can't handle: a variable that doesn't exist, a method called on undefined, a piece of text that was supposed to be JSON but isn't. When that happens, JavaScript throws an error. Unless something catches it, the error stops the current script and shows up in the console in red.

Errors are not the enemy. They are JavaScript telling you, as precisely as it can, what went wrong and where. In this lesson you will learn to read the built-in error types, to catch errors with try...catch so one bad input doesn't crash a whole page, to clean up with finally, and to inspect the error object that every catch block receives.

What happens when an error is thrown

Run this example. Watch which lines print and which don't:

JS An uncaught error stops the script

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Steps 1 and 2 run. Then reading .theme from undefined throws a TypeError, and nothing after it runs. The console shows the error's type, its message and the line where it happened. Those three pieces of information are usually enough to find the bug, so get into the habit of reading them carefully instead of skimming past the red text. The console lesson has more tips for reading messages.

The built-in error types

JavaScript has a handful of error types. Each one is a kind of object made by a constructor with the same name, and each tells you a category of problem:

Type Thrown whenโ€ฆ Example
ReferenceError You use a name that doesn't exist (or a let/const before its declaration). totl + 1 when you meant total
TypeError A value is the wrong kind for the operation. undefined.length, "hi"(), assigning to a const
SyntaxError Code (or text being parsed, like JSON) breaks the grammar rules. JSON.parse("{name: 1}")
RangeError A number is outside the allowed range. new Array(-1), (5).toFixed(500)
URIError A URL-encoding function gets malformed input. decodeURIComponent("%")
AggregateError Several errors are reported together. Promise.any() when every promise fails
EvalError Kept for historical reasons; modern engines don't throw it. โ€”

TypeError and ReferenceError are the ones you will see every day. A SyntaxError in your own source code is special: the engine finds it while reading the script, before anything runs, so the whole script fails and no try...catch inside it can help. A SyntaxError thrown by JSON.parse() at run time, on the other hand, can be caught like any other error.

JS Meet the error types

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The exact messages differ between browsers (Chrome says "Cannot read properties of undefined", Firefox says "undefined has no properties"), but the error names are part of the language and are the same everywhere. That is why code should check the name or type, never the message text.

Catching errors with try...catch

Wrap code that might fail in a try block. If anything inside it throws, JavaScript jumps straight to the catch block and hands it the error. The rest of the program carries on:

JavaScript
try {
  // code that might throw
} catch (error) {
  // runs only if something above threw
}
// execution continues here either way

A classic case is parsing JSON that came from somewhere you don't control, such as a file, an API or a user:

JS Parse JSON safely

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice what happens inside the try block: as soon as JSON.parse() throws, the console.log("Loaded:") line is skipped. Execution never "returns" into the try block after an error.

Keep try blocks small. Wrap only the line or two that can actually fail. A giant try around a whole function makes it hard to tell which line threw, and it can accidentally hide bugs that have nothing to do with the problem you meant to handle.

The catch binding is optional

If you don't need the error object, you can leave out the parentheses. This is called optional catch binding and works in every modern browser:

JavaScript
function isValidJson(text) {
  try {
    JSON.parse(text);
    return true;
  } catch {
    return false;
  }
}

The error object

The value a catch block receives is usually an instance of Error (or one of its subtypes). It carries useful properties:

  • error.name โ€” the type, such as "TypeError".
  • error.message โ€” a human-readable description.
  • error.stack โ€” a text trace of the function calls that led to the error. It isn't part of the official standard, but every browser and Node.js provide it, and it is what the developer console prints.
  • error.cause โ€” an optional earlier error that this one wraps. You'll create these in Throwing and Custom Errors.

Because every error type inherits from Error, you can use instanceof to decide how to respond:

JS Inspect and classify errors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The catch parameter is a normal variable that exists only inside the catch block. Name it whatever reads best: error, err and e are all common.

Not everything thrown is an Error. JavaScript lets code throw any value, even a string or a number. Well-written code always throws Error objects, but if you catch errors from code you didn't write, check before reading .message: error instanceof Error ? error.message : String(error).

Cleaning up with finally

A finally block runs after try and catch, no matter how they ended: normally, with a caught error, or even with a return. Use it for clean-up that must always happen, like hiding a loading spinner, closing a file or releasing a lock.

JS finally always runs

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look closely at the first order: the try block hits return "ok", yet finally still runs before the function actually returns. That guarantee is what makes finally reliable for clean-up.

You can also write try...finally without a catch. The error is not handled; it continues upward after the clean-up runs. That is useful when the current function should tidy up but let a caller decide what to do about the failure.

Don't return from finally. A return inside finally overrides whatever try or catch returned, and it silently throws away any error that was on its way out. Keep finally for clean-up only.

Errors travel up the call stack

When a function throws and doesn't catch the error itself, the error moves up to the function that called it, then to its caller, and so on. The first try...catch it meets on the way up handles it. If none does, it becomes an "uncaught" error in the console.

JavaScript
function readAge(user) {
  return user.profile.age;      // throws if profile is missing
}

function greet(user) {
  return `You are ${readAge(user)}`;  // doesn't catch, so the error passes through
}

try {
  greet({ name: "Sam" });
} catch (error) {
  console.log("Handled at the top:", error.name); // TypeError
}

This means you don't need a try...catch in every function. Catch errors at the level where you can actually do something useful: show a message, use a default, retry, or log the problem.

Where try...catch doesn't help

try...catch only catches errors thrown while the try block is running. Code scheduled to run later, such as a setTimeout callback, runs after the try block has already finished, so its errors escape:

JavaScript
try {
  setTimeout(() => {
    null.boom; // runs later, outside the try block
  }, 100);
} catch (error) {
  console.log("never reached");
}

You'll learn the right patterns for asynchronous code in Asynchronous Callbacks, Promises and async and await.

Good habits

  • Don't swallow errors. An empty catch {} hides bugs. At minimum, log the error with console.error() so you know it happened.
  • Prefer checks for expected situations. If a value is often missing, test for it with an if or optional chaining. Save try...catch for things you can't easily check in advance, like parsing.
  • Handle what you understand, rethrow the rest. If a catch block only knows how to deal with a SyntaxError, throw anything else again. The next lesson shows how.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which error type do you get from undefined.length?

    The value exists but has the wrong type for the operation: undefined has no properties, so reading one throws a TypeError.
  2. 2. What does finally do?

    finally always runs, which makes it the right place for clean-up such as hiding a spinner.
  3. 3. Why should code check error.name or instanceof instead of error.message?

    Each engine writes its own messages, while the error types are defined by the language.
  4. 4. A typo makes your script contain let x = ;. Can a try...catch in the same script catch it?

    Syntax errors in source code are found while the engine reads the script, before any code (including your try block) runs.
  5. 5. What is printed? try { console.log("a"); JSON.parse("x"); console.log("b"); } catch { console.log("c"); }

    a prints, JSON.parse throws, so b is skipped and the catch block prints c.

Summary

  • An uncaught error stops the current script; the console shows its type, message and line.
  • The main types are ReferenceError, TypeError, SyntaxError, RangeError and URIError; names are standard, messages are not.
  • try...catch handles errors thrown while the try block runs, so the rest of the program can continue.
  • The error object has name, message, stack and sometimes cause; use instanceof to classify it.
  • finally always runs, making it ideal for clean-up; never return from it.
  • Errors bubble up the call stack to the nearest try...catch, so catch them where you can respond usefully.

Next: Throwing and Custom Errors โ€” signal problems from your own code with throw, custom error classes and cause.