Errors, try and catch
Errors stop a program
- When JavaScript cannot carry out a line, it throws an error, and the program stops there.
- The message names the kind of error and what went wrong. Read it before changing anything.
ReferenceErrormeans a name does not exist, often a typo.TypeErrormeans a value is the wrong kind, such as calling something that is not a function.
console.log("before");
let total = 5;
console.log(totl); // typo
console.log("after"); // never runs
Output:
before
ReferenceError: totl is not defined
try and catch
- Put the risky code inside
try { … }. - If it throws, the program jumps to
catch (err) { … }instead of stopping. err.messageholds the text of the error. Code after thetry…catchruns either way.
try {
const data = JSON.parse("{ broken");
console.log(data);
} catch (err) {
console.log("Could not read the data");
}
console.log("still running");
// → Could not read the data
// → still running
throw your own error
throw new Error("message")stops the function and hands the error to whoever called it.- Throw when a function gets a value it cannot sensibly use. Catch where you can do something about it.
Worked example: a safe age check
Question: checkAge(age) should throw for an age below 0, and otherwise return "ok". Call it with two ages and report each result.
function checkAge(age) {
if (age < 0) {
throw new Error("age cannot be negative");
}
return "ok";
}
for (const age of [12, -3]) {
try {
console.log(age, checkAge(age));
} catch (err) {
console.log(age, "rejected:", err.message);
}
}
// → 12 ok
// → -3 rejected: age cannot be negative
The try…catch sits inside the loop, so one bad age is reported and the loop still goes on to the next one.
Watch out
catchonly catches errors thrown while thetryblock runs. A typo that breaks the whole program's syntax is never caught.- Do not hide every error with an empty
catch {}. Say what went wrong, or the bug becomes invisible.
Common mistakes
throw "bad age"instead ofthrow new Error("bad age"). Thenerr.messageisundefined.- Putting the
console.logthat uses the result after thetry, where the variable from insidetryno longer exists. - Catching an error and carrying on as if the value were fine. Decide what the program should do instead.
Now you try
- Throw an error for bad input, then catch it and print its message.
- Press Check answer to test it.
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
JSON.parse("oops") throws. Wrap it in try…catch so the program logs bad data from the catch, then logs done after the try…catch.
Clique em Executar para ver a saída aqui.
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
Write divide(a, b). It returns a / b, but when b is 0 it throws new Error("cannot divide by zero").
Clique em Executar para ver a saída aqui.
Dificuldade 3/5 · Moedas 200 + pequeno bônus na primeira conclusão hoje
checkAge is given. Loop over [20, -1, 7]. For each age, log ok when checkAge succeeds, or the error's message when it throws.
Clique em Executar para ver a saída aqui.