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')
try { ... }holds the code that might fail. As soon as one line throws an error, the rest of thetryis skipped, and JavaScript goes directly tocatch.JSON.parse(text)turns text in JSON format into an object. JSON is a text format for data, and the next lesson covers it. If the text is broken,JSON.parsethrows aSyntaxError.throw new Error('...')makes an error of your own (new Error), then throws it (throw). You write the error's message inside the parentheses.catch (error) { ... }only runs when there is an error. The caught error goes into the variableerror:error.nameholds its kind (SyntaxError,Error), anderror.messageholds its message.finally { ... }always runs, with or without an error. It is a good place for cleanup, such as hiding a loader.
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
}
- Once
throwruns, the function stops at that line. So thereturnbelow it never runs. - The code that calls
getDiscountcatches the error withcatch.error.messageholds the text you wrote, exactly, letter for letter. In the exercise, even one extra exclamation mark is wrong. - Always throw a
new Error('...').throwcan in fact throw any value, for example a plain string:throw 'oops'. If that string is caught withcatch (e),typeof eis"string"ande.messageisundefined, so there is no message to read.
⚠️ Why is the error so hard to find?
- An empty
catch.catch (error) {}makes errors disappear silently, so the bug becomes hard to find. At least log the error withconsole.error(error). - One giant
try. Wrap only the part that can really fail, so you know which line an error came from. - Errors from
fetchwithoutawait.fetch(it gets data from a server) gives a Promise: a value that arrives later.try...catchonly catches a Promise's error when you useawait(the keyword that waits for a Promise) inside thetry. The Async/Await lesson covers this.
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.