

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 6
click for more info
Not enough gems
Cost: 6 gems
1: Error Object
incomplete
2: Handling Errors
incomplete
3: Finally
incomplete
4: Throwing Errors
incomplete
5: When to try/catch
incomplete
This lesson's interactive features are locked, please to keep using them
Errors are thrown (and should be thrown by you) when a non-happy path is encountered in your code. For example:
Like Python, when an error is thrown, JavaScript yeets the program out of its current context and into the nearest try/catch block, or, if there isn't one, it crashes the program. For example:
const titan = {};
console.log(titan.neck.thickness);
console.log("done");
The code above prints:
TypeError: Cannot read properties of undefined (reading 'thickness')
It never gets to console.log("done") because the error crashes the program. The same error can happen inside a function:
function getNeckThickness(titan) {
return titan.neck.thickness;
}
Put the potentially error-throwing code in a try block. If an error is thrown, execution immediately jumps to the catch block, skipping any code in try that hasn't run yet:
try {
console.log(getNeckThickness({}));
console.log("what's a titan?");
} catch (err) {
console.log(err.message);
}
console.log("done");
Which prints:
Cannot read properties of undefined (reading 'thickness')
done
A try/catch block lets the program handle errors gracefully without crashing.
Putting code inside a try/catch block is often called "wrapping" the code in it.
One of the calls to getMessageRecord is throwing a text id not found error.