Careeroza
try...catch...finally
Catching Errors
Example
Code in try runs; if it throws, execution jumps to catch. finally always runs:
function parsePrice(text) {
try {
const value = JSON.parse(text);
if (typeof value !== "number") throw new TypeError("Price must be a number");
return value;
} catch (err) {
console.log("Problem:", err.name, "-", err.message);
return 0;
} finally {
console.log("parsePrice finished for", text);
}
}
console.log(parsePrice("499"));
console.log(parsePrice("{oops"));
console.log(parsePrice('"free"'));Output
parsePrice finished for 499
499
Problem: SyntaxError - Expected property name or '}' in JSON at position 1 (line 1 column 2)
parsePrice finished for {oops
0
Problem: TypeError - Price must be a number
parsePrice finished for "free"
0throw
Example
You can throw any value, but always throw Error objects: they carry a message and a stack trace.
function withdraw(balance, amount) {
if (amount > balance) throw new RangeError(`Cannot withdraw ${amount}, balance is ${balance}`);
return balance - amount;
}
withdraw(100, 500);Output
Uncaught RangeError: Cannot withdraw 500, balance is 100