throw Statement
Overview
The throw statement allows developers to intentionally create custom errors.
When you throw, the current function immediately stops executing (exactly like a return statement), and the JavaScript engine looks up the call stack for the nearest catch block to handle the error.
Syntax
function withdrawMoney(amount, balance) {
if (amount > balance) {
// Intentionally halt execution and throw an error!
throw new Error("Insufficient funds!");
}
if (amount < 0) {
throw new Error("Amount must be positive.");
}
return balance - amount;
}
try {
withdrawMoney(500, 100);
} catch (err) {
console.log("Transaction Failed: " + err.message);
}Common Pitfalls
Throwing primitive strings like
throw 'Error!'. While technically allowed by JavaScript, this is terrible practice because a plain string does not have a stack trace (the file and line number where the error occurred). Always throw anErrorobject:throw new Error('Message').
Interview Questions
Why should you always use throw new Error('msg') instead of throw 'msg'?
Throwing an Error object automatically captures the Stack Trace (the exact sequence of function calls and line numbers that led to the crash). A plain string provides no debugging context.
Real-World Example
Validating user input in a registration form and throwing specific errors if the input is unsafe.
function registerUser(username) {
if (username.length < 3) {
throw new Error("Username too short.");
}
// Proceed with registration
}Check Your Knowledge
Test your understanding of throw Statement with these quick questions.