Errors and async · Lesson 34 of 45
Handling errors: try and catch
Keep the program alive when something goes wrong.
When an error happens JavaScript stops the code. try { … } catch (err) { … } lets you “catch” it and handle it instead of crashing. finally runs either way. You can raise your own with throw new Error("…").
- 1function divide(a, b) {
- 2 if (b === 0) throw new Error("Cannot divide by zero")
- 3 return a / b
- 4}
- 5try {
- ▶ console.log(divide(10, 2))
- 7 console.log(divide(1, 0))
- 8 console.log("never printed")
- 9} catch (err) {
- 10 console.log("Error:", err.message)
- 11} finally {
- 12 console.log("done")
- 13}
Variables
—
Output
The first call works.
| Type | Happens when |
|---|---|
| you use a variable that doesn't exist |
| an operation doesn't fit the type ( |
| the code is malformed (or |
| a number is out of range |
What's the output?
try {
null.length
} catch (e) {
console.log(e.name)
}What will this code print?
Complete the code
Raise your own error when the age is negative.
if (age < 0) new Error("Invalid age")
Exercise
Try JSON.parse on the bad text; if it errors, print Invalid JSON.
Expected output: Invalid JSON
const text = "{oops"
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.