Error handling is the process of responding to and managing exceptions (errors) that occur during the execution of code, allowing programs to recover gracefully instead of crashing.
try {
let data = JSON.parse("{ invalid json }");
} catch (error) {
console.error("Caught an error:", error.message);
} finally {
console.log("This always runs.");
}
function divide(a, b) {
if (b === 0) throw new Error("Cannot divide by zero!");
return a / b;
}
name โ Type of errormessage โ Details about the errorstack โ Call stack traceReferenceErrorTypeErrorSyntaxErrorRangeErrorEvalErrorURIErrorasync function fetchUser() {
try {
let res = await fetch("https://jsonplaceholder.typicode.com/users/1");
let user = await res.json();
console.log(user);
} catch (err) {
console.error("Failed to load user:", err.message);
}
}
async/await and handles failures.throw if age input is less than 18.The script will stop running and a message will be shown in the browser console.
Yes, wrap the await calls in a try-catch block to handle asynchronous errors.
Use it when you expect possible runtime errors and want to prevent app crashes.
try-catch works with async/await, while .catch() is used with promise chains.
try-catch and throw to trap and define issuestry-catch