Throwing Your Own Errors
The welcome video’s JavaScript report rejected two rows with the reason ValueError is not
defined. You found out why by porting the line of Joan’s Python script that refuses line 6’s
refund, -40.00: parse_amount() raises its own ValueError, whose message says what arrived.
- The port follows the Python line by line.
float()becomesNumber(), which gives the same number for this refund, butNaNforn/a.raisebecomesthrow, with the same job: it stops the function and sends the error up to the nearestcatch. Where Python calls the class, JavaScript puts thenewkeyword in front.exceptbecomescatch, which names no type, anderr.namegives the error’s type as text. - It logs the wrong problem. The port logs
ReferenceError - ValueError is not defined, not the refund’s message. The line failed beforethrowcould run: JavaScript has noValueError,KeyErrororIndexErrorclass, and naming a class that doesn’t exist throws aReferenceError, which plays the part of Python’sNameErrorhere. catchtook that error too. Unlikeexcept ValueError,catchtakes every error, so it received this one and logged it in place of the refund’s problem. That’s the reason the welcome video’s report gave for two rows: the refund, and the blank amount on line 4, sinceNumber()turns blank text into0.- The fix changes only the class.
Erroris JavaScript’s general error class, much likeExceptionin Python. Unlike a bareExceptionin Python, a plainErroris normal JavaScript, not a shortcut: most code throws one. Your ownValueErrorclass comes later on the path, with classes.
function parseAmount(text) {
const amount = Number(text);
if (amount <= 0) {
throw new Error(
`amount must be positive, got ${amount}`,
);
}
return amount;
}
try {
parseAmount("-40.00");
} catch (err) {
console.log(err.name, "-", err.message);
}
It logs the refund’s own problem: