Errors, try and catch
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
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.
English
console.log("before");
let total = 5;
console.log(totl); // typo
console.log("after"); // never runs
Output:
before
ReferenceError: totl is not defined
English
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.

English
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
English
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.
English
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.
English
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.
English
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.
English
Now you try
- Throw an error for bad input, then catch it and print its message.
- Press Check answer to test it.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
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.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Write divide(a, b). It returns a / b, but when b is(是) 0 it throws new Error("cannot divide by zero").
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
checkAge is given. Loop over [20, -1, 7]. For each age, log ok when checkAge succeeds, or the error's message when it throws.
点击“运行”查看此处输出。