JAVASCRIPT

Throwing Errors


 

Throwing errors in JavaScript is a fundamental aspect of error handling and is typically done using the throw statement.

Here's a simple example:
 

// throw error
function checkAge(age) {
    if (typeof age !== 'number') {
        throw "Age must be a number";
    }
    if (age < 0) {
        throw "Age cannot be negative";
    }
    if (age >= 120) {
        throw "Are you sure this is your age?";
    }
    return "Age is valid";
}

try {
    var result = checkAge(25);
    console.log(result);
    
    // Uncomment these lines to test different scenarios
    // var result = checkAge("not a number");
    // var result = checkAge(-5);
    // var result = checkAge(150);
} catch (error) {
    console.error("Error occurred:", error);
}

 

Note: It allows us to throw custom error