Tale~9 min
An inspection at the warehouse
Runtime errors, throw, try...catch and finally.
I've been appointed safety inspector. My job is to find breakages before they bring down the whole warehouse. In a program, a breakage is called an error (an exception).
JSexample
const box = null;
try {
console.log(box.weight);
} catch (error) {
console.log(error.name);
console.log(error.message);
}null — JavaScript throws a TypeError.When an error happens while running, JavaScript throws it: the current code is interrupted, and the error travels upwards until it's caught. If nobody catches it, the program stops.
try { … } catch (error) { … } catches an error: if the code in try breaks, execution jumps to catch, and error holds the error object with name and message fields.
Common built-in errors:
TypeError— an operation on an unsuitable value: a property of undefined, calling something that isn't a function;ReferenceError— the variable isn't declared;SyntaxError— code or JSON is written incorrectly (in JSON.parse, for example).
You can throw an error yourself too — when carrying on is impossible. For that, throw new Error("message").
JSexample
function checkWeight(kg) {
if (kg > 100) throw new Error("Overload!");
return "Cargo accepted";
}
try {
console.log(checkWeight(20));
console.log(checkWeight(500));
console.log("never reached");
} catch (error) {
console.log("Inspector: " + error.message);
}throw, the code in try is interrupted — the third line never runs.finally runs always — after success and after an error. Clean-up goes there: hide a loading spinner, close a file.
JSexample
function inspect(kg) {
try {
if (kg > 100) throw new Error("Overload");
return "ok";
} catch (error) {
return "rejected: " + error.message;
} finally {
console.log("Inspection over");
}
}
console.log(inspect(5));
console.log(inspect(200));finally fires in both cases.An inspector isn't someone who forbids breaking. An inspector is someone who knows in advance what to do when it breaks. And who always has a spare fish.
Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.
Question 1 of 3