About Lesson
try…catch Block
The try…catch block lets you test code that might throw an error (in the try block) and catch any resulting errors (in the catch block), where you can handle them gracefully.
Syntax:
JavaScript
try {
// Code that may cause an error
} catch (error) {
// Code to handle the error
}
Example:
JavaScript
try {
let data = 10 / x; // Invalid code
} catch (error) {
console.log("Error:", error.message);
}
In this example, an invalid JSON string causes an error, which the catch block handles, logging a message to the console.
Real-Life Example: Form Validation
Imagine a form where users enter their age. If they enter text instead of a number, the program should handle this without crashing.
JavaScript
function validateAge(age) {
try {
if (isNaN(age)) {
throw new Error("Age must be a number!");
} else if (age < 0 || age > 120) {
throw new Error("Age must be between 0 and 120.");
} else {
console.log("Age is valid:", age);
}
} catch (error) {
console.log("Error:", error.message);
}
}
validateAge("twenty"); // Error: Age must be a number!
validateAge(150); // Error: Age must be between 0 and 120.
validateAge(25); // Age is valid: 25
In this example, validateAge checks if the age is a number and within a valid range. If the input is invalid, an error is thrown and handled in the catch block.