javascript · level 3 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
raises the alarm; decides what happens next.
So far an error stopped your whole program. Professionals plan for errors. throw new Error("message") stops the current function on purpose and passes the error upwards, through every caller, until something catches it.
Wrap risky code in try...catch. If anything inside try throws, JavaScript jumps to catch (error), where error.name and error.message tell you what happened. A block runs afterwards either way, perfect for tidying up.
function parseAge(text) {
const age = Number(text);
if (Number.isNaN(age)) { throw new Error(`"${text}" is not a number`); }
return age;
}
for (const input of ["42", "forty"]) {
try {
console.log(`Age ${parseAge(input)}`);
} catch (error) {
console.log(`${error.name}: ${error.message}`);
} finally {
console.log(`Checked ${input}`);
}
} Number("forty") gives NaN, short for Not a Number, and Number.isNaN spots it.
guess first
An error three calls deep. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function step3() { throw new Error("disk full"); }
function step2() { step3(); console.log("step 2 done"); }
function step1() {
try {
step2();
} catch (error) {
console.log(`Caught: ${error.message}`);
}
console.log("step 1 carries on");
}
step1();
your turn
Your turn. Refuse a silly volume.
Pick a good volume from 0 to 10 for the first blank, then a bad one, like 11 or -3, for the second. Watch catch turn the crash into a friendly message.
fix it
The default settings never load. Can you fix it?
- Which line throws the SyntaxError? Is that line inside the
tryblock? JSON.parsefails on line 4, before thetryeven starts, so nothing catches it.- Move the
const settings = ...line inside thetryblock, above theconsole.log.
nailed it
you can catch trouble before it spreads. :D
throwstops a function and sends an error upwards.try...catchcatches it, so the program keeps going.finallyalways runs, error or not.
new words in your collection
- throw
- try...catch
- finally
This lesson isn’t saved. A free account remembers every lesson you finish.