JavaScript Error Handling
Errors can occur in your code, and JavaScript provides mechanisms to handle them gracefully.
try...catch Statement
The try...catch statement allows you to handle errors without stopping the execution of your program.
try {
let result = 10 / 0;
console.log(result);
} catch (error) {
console.log("An error occurred:", error.message);
}
finally Block
The finally block is executed after the try and catch blocks, regardless of whether an error occurred.
try {
let result = JSON.parse("invalid JSON");
} catch (error) {
console.log("Error:", error.message);
} finally {
console.log("Execution completed.");
}
Throwing Errors
You can throw custom errors using the throw statement.
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed.");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (error) {
console.log("Error:", error.message);
}