Error handling helps prevent your code from crashing and allows you to respond to issues in a graceful way.
Use try...catch
to handle exceptions and finally
to execute code regardless of success:
try {
let x = 10;
let y = 0;
let result = x / y;
if (!isFinite(result)) {
throw new Error("Cannot divide by zero");
}
} catch (error) {
console.log(error.message); // Outputs: Cannot divide by zero
} finally {
console.log("This will run regardless of success or error.");
}
Write a function that catches an error when dividing by zero and displays an alert.
try...catch
statement?finally
do in error handling?Answers: To handle exceptions; executes code regardless of success; can crash the script if not handled.