Error Handling — JavaScript

try...catch catches an error so the program does not stop. try holds the code that might fail. catch (error) only runs when there is an error, and the error's…

A profile page loads a user's data. One day the data arrives broken: one curly brace is missing. If the code is not ready for that, the line that reads the data fails, and all the code after it stops. Buttons don't work, and the loader (the spinning "loading" sign) never stops. Visitors only see a page that is stuck.

An error is a problem that appears while your code is running, like the broken data on that profile page. Code that causes an error is said to throw an error. If nothing handles it, one error stops all the code after it. try...catch catches that error. Then you decide what happens next, and the program continues.

Catch errors with try...catch

The function loadProfile below reads the text of a user's data, then greets that user.

function loadProfile(text) {
  try {
    const user = JSON.parse(text)
    if (!user.name) {
      throw new Error('name is required')
    }
    console.log('Hello, ' + user.name)
  } catch (error) {
    console.log(error.name + ': ' + error.message)
  } finally {
    console.log('Loader hidden')
  }
}

loadProfile('{"name":"Budi"}')
console.log('The program goes on')

When loadProfile is called with '{"name":"Budi"}', it prints Hello, Budi, Loader hidden, then The program goes on. When it is called with '{}', the object has no name. So the throw runs, and the Hello line is skipped. It prints Error: name is required, Loader hidden, then The program goes on.

Without a catch block, the error leaves the function uncaught. finally still runs, but the program stops after that, so The program goes on never prints.

Give back a fallback value from catch

You can write return inside try and inside catch. If the code in try works, the function returns the value from try. If it fails, the function returns the value from catch. That is the fallback value:

function readData(text) {
  try {
    return JSON.parse(text)
  } catch (error) {
    return null
  }
}

readData('{"city":"Leeds"}')   // { city: 'Leeds' }
readData('[1,2,3]')            // [1, 2, 3]
readData('city Leeds')         // null
readData('')                   // null

Let JSON.parse decide whether the text is valid. Don't check it yourself with text.startsWith('{'). An array like [1,2,3] is valid JSON too, although it does not start with a curly brace. Empty text '' and an incomplete object like '{"city":' are not JSON, so both make JSON.parse throw an error.

Throw your own errors with throw

In JavaScript, not every strange thing becomes an error. One example is 10 / 0: it gives Infinity, not an error. If you think a value should count as wrong, check the value yourself, then throw an error. The function below refuses a discount above 100 percent:

function getDiscount(percent) {
  if (percent > 100) {
    throw new Error('A discount can be 100 percent at most')
  }
  return percent / 100
}

try {
  getDiscount(150)
} catch (error) {
  console.log(error.message) // A discount can be 100 percent at most
}

⚠️ Why is the error so hard to find?

TL;DR: try...catch catches an error so the program does not stop. try holds the code that might fail. catch (error) only runs when there is an error, and the error's message is in error.message. finally always runs. The lines after an error inside try are skipped, and an error that nothing catches stops the rest of the program. A return inside catch gives back a fallback value when try fails, such as null. Throw your own errors with throw new Error('message'), not throw 'message', so that error.message holds your message.

⚡ Catch the error, the program keeps going

Write:

try {
  const user = JSON.parse(text)
  console.log('Hello, ' + user.name)
} catch (error) {
  console.log(error.name + ': ' + error.message)
} finally {
  console.log('Loader hidden')
}
Guess first: JSON.parse(text) turns the text of the data into an object, and throws an error (fails) if the text is broken. If the text is broken, does the Hello line still run?

No. As soon as the error is thrown, the rest of the try is skipped, and JavaScript goes directly to catch.

Meaning: Without try...catch, one error stops all the code after it. You write the code that might fail inside try. catch only runs when there is an error: the error's kind is in error.name, and its message is in error.message. finally always runs, with or without an error, so it is a good place for cleanup such as hiding a loader (the spinning "loading" sign).

⚡ A fallback value from catch

Write:

function readData(text) {
  try {
    return JSON.parse(text)
  } catch (error) {
    return null
  }
}

Meaning: If JSON.parse works, readData returns the result from try. If the text is not valid data, JSON.parse throws an error, and readData returns the fallback value from catch, here null. Let JSON.parse decide whether the text is valid, and don't check it yourself.

⚡ Throw your own error

Write:

if (percent > 100) {
  throw new Error('A discount can be 100 percent at most')
}
Guess first: does 10 / 0 throw an error?

No. It gives Infinity. If you think a value should count as wrong, check the value yourself, then throw an error.

Meaning: throw throws an error of your own, here when percent is above 100. Once throw runs, the function that holds that line stops there. Always throw a new Error('...'), not plain text, so that error.message in catch holds your message.

What you will learn