The try…catch statement in JavaScript is used to handle runtime errors without stopping the execution of your program. It allows you to write safer code by catching errors and responding to them properly.
try {
// Code that may cause an error
} catch (error) {
// Code to handle the error
}
try {
let result = JSON.parse('{name: "John"}');
} catch (error) {
console.log("Invalid JSON format");
}
try {
undefinedFunction();
} catch (error) {
console.log(error.name); // ReferenceError
console.log(error.message); // undefinedFunction is not defined
}
try {
console.log("Trying...");
} catch (error) {
console.log("Error occurred");
} finally {
console.log("Execution completed");
}
async function loadData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.log("Failed to load data");
}
}
try {
setTimeout(() => {
undefinedFunction();
}, 1000);
} catch (error) {
console.log("This will NOT catch the error");
}