Learn JavaScript
Lesson 1 - Introduction To JavaScript
Lesson 2 - Basic JavaScript Syntax
Lesson 3 - Control Flow
Lesson 4 - Functions
Lesson 5 - Basic Data Structures
Lesson 6 - Basic String Operations
Lesson 7 - Basic Array Operations
Lesson 9 - Packages
Lesson 10 - User Input
JavaScript allows you to raise an error when a user provides invalid input using the throw
keyword.
Raising exceptions helps you handle errors gracefully, especially when there's a possibility of invalid input from the user.
For example, if a user provides an invalid email address in an input field, you can raise an error to generate a user-friendly message, notifying them that the input is invalid.
function divide(x, y) { if (y === 0) { throw new Error("Division by zero"); } return x / y; } try { let result = divide(10, 0); console.log(result); } catch (error) { console.log("An error occurred:", error.message); }
In our above program, we declared a function divide()
that mathematically divides two variables, x
and y
. We raise an error when the function tries to perform an invalid operation, like dividing 10
by 0
.