Throwing Errors
JS · Error Handlingsyntax
throw new Error(message);
throw new TypeError(message);example
function withdraw(account, amount) {
if (amount <= 0) {
throw new RangeError("Withdrawal amount must be positive");
}
if (amount > account.balance) {
throw new Error("Insufficient funds");
}
account.balance -= amount;
return account.balance;
}Note Always throw Error objects (not strings) so you get a stack trace. Use specific error types (TypeError, RangeError) when appropriate.