Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 8 - Exception Handling

8.3 Raising Exceptions

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.