try. . . catch
Catches errors thrown in the try block and handles them in catch. The optional finally always runs.
Example
#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}'))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
#try {
// code that might throw
} catch (error) {
// handle the error
} finally {
// always runs
}More examples
#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))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()try {
const user = null
console.log(user.name)
} catch (error) {
if (error instanceof TypeError) {
console.log('No user')
} else {
throw error
}
}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 withconsole.error(). - Wrap only the part that might fail in
try, likeJSON.parse()orfetch(), 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, checkerror.nameorinstanceof, noterror.message.
Related entries
#- throwThrows an exception: stops the current code and passes the error to the nearest catch block.
- async functionDeclares an asynchronous function that always returns a promise and can use the await keyword inside it.
- awaitPauses an async function until a promise settles, then returns its value or throws its error.
- Promise.prototype.catch()Registers an error-handling function that runs when the promise is rejected.
- JSON.parse()Converts a string in JSON format into a JavaScript value, such as an object or array.
Spotted a mistake or missing an example? Write to us.