try...catch

Catches errors thrown in the try block and handles them in catch. The optional finally always runs.

On this page

Example

#
JavaScript
function parseProfile(json) {
  try {
    const profile = JSON.parse(json)
    return `Hello, ${profile.name}!`
  } catch (error) {
    return `Invalid data: ${error.name}`
  }
}

console.log(parseProfile('{"name":"Emma"}'))
console.log(parseProfile('{name: Emma}'))
Console
Hello, Emma!
Invalid data: SyntaxError

Definition and usage

#

You put code that might throw an error inside a try block. If something goes wrong, execution stops at the point of the error and moves to catch, which receives the error object. The program keeps running instead of stopping with a message in the console.

The finally block always runs: after a successful try, after a handled error, and even when a return fired inside. It’s a good place for cleanup, like hiding a loading indicator. If you don’t need the error object, you can omit the parentheses: catch { }.

try...catch catches synchronous errors, as well as ones from await inside an async function. It won’t catch an error from a callback that runs later, like one inside setTimeout(). Only catch errors you can meaningfully handle, and pass the rest along with throw.

Syntax

#
Syntax
try {
  // code that might throw
} catch (error) {
  // handle the error
} finally {
  // always runs
}

More examples

#
finally always runs
JavaScript
function loadLesson(id) {
  console.log('Loading...')
  try {
    if (id < 1) {
      throw new Error('Invalid id')
    }
    return `Lesson ${id}`
  } catch (error) {
    return error.message
  } finally {
    console.log('Done loading')
  }
}

console.log(loadLesson(3))
console.log(loadLesson(0))
Console
Loading...
Done loading
Lesson 3
Loading...
Done loading
Invalid id
Errors with await
JavaScript
async function fetchScore() {
  throw new Error('Server unavailable')
}

async function showScore() {
  try {
    const score = await fetchScore()
    console.log(score)
  } catch (error) {
    console.log('Failed:', error.message)
  }
}

await showScore()
Console
Failed: Server unavailable
Recognizing the kind of error
JavaScript
try {
  const user = null
  console.log(user.name)
} catch (error) {
  if (error instanceof TypeError) {
    console.log('No user')
  } else {
    throw error
  }
}
Console
No user

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Don’t leave an empty catch. An error swallowed without a trace means hours of hunting for the cause. At the very least, log it with console.error().
  • Wrap only the part that might fail in try, like JSON.parse() or fetch(), not the whole program.
  • The text of errors thrown by the engine (for example when reading from null) differs between browsers. In your program’s logic, check error.name or instanceof, not error.message.

Related entries

#

Spotted a mistake or missing an example? Write to us.