Throwing errors in JavaScript is the standard way to stop bad data or invalid state from moving forward. It gives you a clean way to signal that something went wrong and let the caller handle it.
The most common pattern is throw with try...catch, and you can also create custom errors when the built-in types are not specific enough. If you need the companion error-handling pattern, JavaScript try catch is the natural related article.
Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.
Method 1: Throw a built-in error
A built-in Error object is enough for many validation failures.
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log("throw-errors:", divide(10, 0));
} catch (err) {
console.log("throw-errors:", err.message);
}You should see one line logging throw-errors: Cannot divide by zero.
Use this when the caller needs a clear failure message instead of a silent wrong result.
Method 2: Catch errors with try...catch
catch lets you handle the exception before it breaks the rest of the flow.
try {
throw new TypeError("Bad input");
} catch (error) {
console.log("throw-type:", error.name);
}You should see one line logging throw-type: TypeError.
This is the right pattern when you want to convert a thrown error into a controlled response.
Method 3: Throw a custom error
A custom message can make validation failures easier to debug.
class ValidationError extends Error {}
try {
throw new ValidationError("Email is required");
} catch (error) {
console.log("throw-custom:", error.name, error.message);
}You should see one line logging throw-custom: ValidationError Email is required.
Use custom errors when the calling code needs a specific error category.
Summary
To throw errors in JavaScript, use throw with a built-in Error, catch it with try...catch, or define a custom error type when you need more control. That approach keeps validation and runtime failures explicit and easier to handle.
