You can throw an error yourself when something is wrong and your function cannot continue.
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 2)); // → 5
console.log(divide(1, 0));
} catch (error) {
console.log("Error:", error.message); // → Error: Cannot divide by zero
}
throw stops the function immediately and passes the error up to the nearest catch.
Throw Error objects
JavaScript lets you throw anything, even a string or a number. Always throw Error objects. They carry a stack trace that shows where the problem occurred, and they work with tools and instanceof.
throw "something went wrong"; // legal, but bad: no stack trace
throw new Error("something went wrong"); // good
Validating input
Throwing is a good way to reject invalid arguments early.
function setAge(age) {
if (typeof age !== "number" || Number.isNaN(age)) {
throw new TypeError("Age must be a number");
}
if (age < 0 || age > 150) {
throw new RangeError("Age must be between 0 and 150");
}
return age;
}
for (const input of [30, -5, "abc"]) {
try {
console.log("OK:", setAge(input));
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}
}
The cause option
When you catch an error and throw a new one with a friendlier message, keep the original in cause.
function loadConfig(text) {
try {
return JSON.parse(text);
} catch (error) {
throw new Error("Invalid configuration file", { cause: error });
}
}
try {
loadConfig("{oops");
} catch (error) {
console.log(error.message); // → Invalid configuration file
console.log(error.cause.name); // → SyntaxError
}
Where an error goes
If nothing catches it, the error travels up through the calling functions, and if it reaches the top, the browser prints it in the console and the current task stops.
function a() { b(); }
function b() { throw new Error("from b"); }
try {
a();
} catch (error) {
console.log(error.message); // → from b
}
Throw or return?
| Situation | Better |
|---|---|
| A programmer made a mistake (wrong argument type) | throw |
| Something unexpected stopped the work | throw |
| An expected outcome (“not found”, “no match”) | return null or undefined |
| User typed invalid data | validate and show a message, do not throw |
Rethrowing
catch, you can throw error again if you cannot handle it. That lets a higher level deal with it.