In JavaScript, errors can be thrown using the throw
statement and can be caught using the try...catch
statement. Here are some examples of how to throw and catch three common types of errors in JavaScript:
Throw and catch a RangeError, ReferenceError, TypeError in JavaScript examples
Simple example code.
RangeError: A RangeError is thrown when a numeric value is not within its valid range.
function divide(a, b) {
if (b === 0) {
throw new RangeError("Cannot divide by zero");
}
return a / b;
}
try {
let result = divide(10, 0);
console.log(result);
} catch (error) {
console.error(error);
}
Output:
ReferenceError: A ReferenceError is thrown when an attempt is made to access a variable or function that does not exist.
try {
let x = y + 1;
console.log(x);
} catch (error) {
console.error(error);
}
Output: ReferenceError: y is not defined
TypeError: A TypeError is thrown when an operation is performed on a data type that is not supported.
try {
let x = null;
x.toUpperCase();
} catch (error) {
console.error(error);
}
Output: TypeError: Cannot read property ‘toUpperCase’ of null
In each of these examples, the try…catch statement is used to catch the thrown error and log it to the console. It’s important to note that catching errors in this way can help prevent your program from crashing, and can also help you identify and fix bugs more easily.”
Do comment if you have any doubts on this Js error topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version