About Lesson
Throwing Custom Errors
JavaScript lets you throw custom errors using the throw statement. This is helpful for communicating specific problems that may arise in the code, making it easier to debug.
Syntax:
JavaScript
throw new Error("Custom error message");
Example: Validating User Input in a Shopping Cart
Suppose you’re building a shopping cart and want to validate that the quantity entered by the user is positive.
JavaScript
function updateCart(quantity) {
try {
if (quantity <= 0) {
throw new Error("Quantity must be greater than zero.");
}
console.log("Quantity updated to:", quantity);
} catch (error) {
console.log("Cart Error:", error.message);
}
}
updateCart(-5); // Cart Error: Quantity must be greater than zero.
updateCart(3); // Quantity updated to: 3
In this example, if a user enters a negative quantity, a custom error is thrown, providing a specific error message.