Discuss Error Handling in JavaScript Using Suitable Example.
Discuss Error Handling in JavaScript Using Suitable Example.
Syntax
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that will always run, regardless of an error
}
HTML
JavaScript (app.js)
function executeWithErrorHandling() {
const outputElement = document.getElementById('output');
outputElement.innerHTML = ""; // Clear previous output
try {
// Code that may throw an error
let result = riskyOperation();
outputElement.innerHTML = "Operation successful: " +
result;
} catch (error) {
// Code to handle the error
outputElement.innerHTML = "An error occurred: " + err
or.message;
} finally {
// Code that will always run, regardless of an error
outputElement.innerHTML += "<br>Execution complete.";
}
function riskyOperation() {
// Simulate an error
let num = Math.random();
if (num < 0.5) {
throw new Error("Random error occurred!");
}
return num;
}
Explanation
1. HTML Structure:
2. JavaScript Code:
executeWithErrorHandling Function:
try Block: Calls the riskyOperation function, which may throw an error.
If the operation is successful, it displays the result.
catchBlock: Catches any errors thrown in the try block and displays
an error message.
3. riskyOperation Function:
If the number is less than 0.5, it throws a new error with a custom
message.
Example:
function validateAge(age) {
if (age < 0 || age > 120) {
throw new Error("Invalid age provided!");
}
return "Valid age: " + age;
}
try {
console.log(validateAge(25)); // Valid case
console.log(validateAge(-5)); // Invalid case, will thro
w an error
} catch (error) {
console.error("Error: " + error.message);
}
Explanation:
The validateAge function checks if the provided age is within a valid range.
By understanding and utilizing error handling in JavaScript, you can write more
robust and reliable code that can gracefully handle unexpected situations and
provide meaningful feedback to users and developers.