This error occurs when an exception
(an unexpected event that disrupts the normal flow of execution) is thrown but
not caught by any catch block in the code. For example:
function divide(a,b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
console.log(divide(10,0));
The code above will throw an uncaught exception because there is no catch
block to handle the Error object thrown by divide(). To fix this error,
we need to add a catch block after the try block that calls divide():
function divide(a,b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (error) {
console.error(error.message);
}
try {
console.log(divide(10, 2));
} catch (error) {
console.error(error.message);
}
To avoid this error, make sure to use `try…catch` blocks wherever appropriate
and handle different types of exceptions accordingly.