throw
`throw` stops the current function and sends an error up to whoever called it.
throw raises a value as an error. Almost always it is a new Error("message"), because an Error keeps the message and the call stack, which tell you where it failed.
When throw runs, the rest of that function does not run. The error travels up to the caller, and on up until a try / catch catches it. If nobody does, Node ends the program with a message.
That is why it is used to reject invalid data: failing early with a clear message beats carrying on with a broken value. The course uses it like this: throw new Error(Invalid quantity: "${text}");, with a template literal that includes the value that caused the problem.
You can throw any value, but always throw an Error (or a subclass).
Reach for it when: a function gets something it cannot accept and carrying on would be worse than stopping.
Examples
Common mistake
function check(n: number): string {
if (n < 0) {
throw "negative";
}
return "ok";
}
try {
check(-1);
} catch (error) {
console.log(typeof error);
console.log(error instanceof Error);
}Why: Throwing a string works, but it has no stack or `message`, and `instanceof Error` is false. It is hard to debug.
How to write it: Throw an Error: throw new Error("negative").
