🤮 Throw Statement in Action
The throw statement is used to manually create (or throw) an error in JavaScript.
You can throw custom errors using throw, and it will immediately stop the execution of code in the current block and transfer control to the nearest catch block.
You can throw:
Errorobject:throw new Error("message")A string:
throw "Something went wrong"A number, boolean, object, etc.
An instance of
Error,TypeError,ReferenceError, etc. (✅ recommended)
This is useful when:
You want to stop the execution under invalid conditions
You want to signal an error condition
You want to customize error messages
🔧 Syntax
throw expression;🐞 Throwing a String (Not recommended for large apps)
try {
throw "Something went wrong!";
} catch (err) {
console.log("Caught error:", err);
}Caught error: Something went wrong!🔴 Drawback: err is just a string — it doesn't have name, message, or stack trace.
🐛 Throwing a Built-in Error Object (Recommended)
try {
throw new Error("Invalid operation");
} catch (err) {
console.log("Error name:", err.name); // Error
console.log("Error message:", err.message); // Invalid operation
}Error name: Error
Error message: Invalid operation🧠 Using Error gives access to:
.name.message.stack(useful for debugging)
📚 Types of Built-in Error Objects You Can Throw
JavaScript has built-in error types like:
Error Type | Description |
|---|---|
| Generic error |
| Wrong data type used |
| Accessing a variable that’s not defined |
| Parsing code with invalid syntax (usually caught at compile time) |
| A number is out of an allowed range |
Example: Throwing a TypeError
function divide(a, b) {
if (typeof a !== "number" || typeof b !== "number") {
throw new TypeError("Both arguments must be numbers.");
}
return a / b;
}
try {
divide("10", 2);
} catch (err) {
console.log("Caught:", err.name); // TypeError
console.log("Message:", err.message); // Both arguments must be numbers.
}Caught: TypeError
Message: Both arguments must be numbersExample: Throwing a RangeError
function validateAge(age) {
if (age < 0) {
throw new RangeError("Age cannot be negative");
}
console.log("Age is valid:", age);
}
try {
validateAge(-5);
} catch (error) {
console.log("🚫 Error Type:", error.name); // RangeError
console.log("📩 Message:", error.message); // Age cannot be negative
}🚫 Error Type: RangeError
📩 Message: Age cannot be negative🔄 Execution Flow with throw
function test() {
console.log("Before throw");
throw new Error("Something broke");
console.log("After throw"); // ❌ Never runs
}
try {
test();
} catch (e) {
console.log("Caught:", e.message);
}Before throw
Caught: Something broke🔥 Once throw is executed, control immediately jumps to the nearest catch block, and the remaining code in the try block is skipped.
✅ Best Practices
Tip | Why It Matters |
|---|---|
Always use | Helps with debugging and consistent handling |
Avoid throwing strings | Strings lack error metadata |
Use | Don’t wrap your entire program unnecessarily |
Validate input and throw when needed | Makes your code defensive and robust |