Errors and try…catch

Topic 1 of 3 in Error handling7 min readBeginnerFree course

Overview

When something goes wrong, JavaScript throws an error. If nothing catches it, the script stops and the error appears in the console.

JavaScript
JSON.parse('not json'); // SyntaxError
console.log('never reached');

Errors aren’t a sign you’ve failed — they’re how programs report problems. Data from users and servers is often missing or malformed, networks drop, files don’t exist. Good code expects this and handles the error: it shows a helpful message, uses a fallback, or tries again, instead of breaking the whole page.

Catching errors

JavaScript
try {
  const data = JSON.parse(text);
  show(data);
} catch (error) {
  console.error('Could not read the data:', error.message);
  showMessage('Something went wrong. Please try again.');
} finally {
  hideSpinner(); // runs whether or not there was an error
}

Flowchart: the try block runs; if nothing throws, the rest of try runs; if something throws, control jumps to catch(error); finally runs either way. Beside it, divide() throws an error, calc() doesn’t catch it so it passes up, and main() catches it. With no catch anywhere, the script stops.

  • try wraps code that might fail. As soon as a line throws, the rest of the block is skipped.
  • catch (error) runs only if something threw. error is the thrown value. If you don’t need it, you can write just catch { … }.
  • finally runs afterwards in every case — success, error, even a return inside try. It’s the place for clean-up: hiding a loading spinner, closing a connection.

You need try plus at least one of catch or finally.

Errors travel up

An error doesn’t have to be caught where it happens. If a function doesn’t catch it, it passes to the function that called it, and so on up the call stack, until a try…catch handles it — or it reaches the top and stops the script.

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

function calc() {
  return divide(10, 0); // doesn't catch — the error passes up
}

try {
  calc();
} catch (error) {
  console.log(error.message); // 'Cannot divide by zero'
}

This lets you catch errors at the level that knows what to do about them — often near the user interface — rather than in every small function.

The error object

Errors are objects with useful properties:

JavaScript
try {
  null.length;
} catch (error) {
  error.name;    // 'TypeError'
  error.message; // "Cannot read properties of null (reading 'length')"
  error.stack;   // the message plus the list of functions and lines
}

Throwing your own

When a function gets input it can’t handle, throw an error instead of returning a confusing value:

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

Compare the alternatives: returning Infinity, null or -1 forces every caller to remember to check, and if they forget, the bad value spreads silently through the program. An error is loud and points straight to the cause.

Always throw Error objects. You can throw 'oops', but a string has no stack trace and no name, which makes debugging much harder.

Built-in error types

Type Typical cause
Error The general type — use it for your own errors
TypeError Using a value the wrong way, e.g. calling undefined() or reading a property of null
ReferenceError Using a variable that doesn’t exist
SyntaxError Code or JSON that can’t be parsed
RangeError A number outside the allowed range, e.g. new Array(-1)
URIError Badly formed URL encoding, e.g. decodeURIComponent('%')

You can throw these yourself when they fit: throw new TypeError('Expected a string').

Handling different errors differently

catch receives every kind of error. Use instanceof (or error.name) to react to the ones you expect and re-throw the rest:

JavaScript
try {
  const settings = JSON.parse(saved);
  applySettings(settings);
} catch (error) {
  if (error instanceof SyntaxError) {
    applySettings(DEFAULTS); // corrupted data — fall back
  } else {
    throw error; // something unexpected — don't hide it
  }
}

The next topic shows how to create your own error types for this.

Errors in asynchronous code

A try…catch only catches errors thrown while it is running. A callback that runs later is outside it:

JavaScript
try {
  setTimeout(() => {
    throw new Error('Too late!'); // NOT caught — try finished long ago
  }, 100);
} catch (e) {
  console.log('never runs');
}

With promises, use .catch(), or await the promise inside try:

JavaScript
async function load() {
  try {
    const res = await fetch('/api/data'); // rejection is thrown here
    return await res.json();
  } catch (error) {
    console.error('Load failed', error);
  }
}

You’ll see much more of this in Promises and async / await.

Good habits

Don’t swallow errors. An empty catch {} hides bugs. At the very least, log the error.

  • Catch narrowly. Wrap only the code that can fail, not the whole program.
  • Catch where you can act. If you can’t show a message, retry or fall back, let the error travel up.
  • Give users a helpful message, and keep the technical details in the console.
  • Validate early. Check input at the start of a function and throw straight away, before anything has been half-changed.
Exercise

Validate an age

Write parseAge(text) that returns a number, or throws a RangeError if it’s not a whole number from 0 to 130. Then write safeAge(text) that calls parseAge and returns null instead of throwing.

JavaScript
function parseAge(text) {
  // your code here
}

function safeAge(text) {
  // your code here
}

Summary

  • throw stops the current code and passes an error up the call stack until something catches it.
  • try…catch handles an error; finally always runs, error or not.
  • Throw Error objects (not strings) so you get a message and a stack trace.
  • Only catch errors you can do something useful about — and never swallow them silently.
  • try…catch only catches errors in async code when you await inside it.