Concept | Description |
---|---|
try...catch...finally |
Handles runtime errors, ensures cleanup. |
throw |
Manually trigger errors. |
Error Object | Includes name , message , stack . |
Error Types | TypeError , ReferenceError , SyntaxError , etc. |
Sync Errors | Caught by try...catch . |
Async Errors | Not caught unless inside async function or handled via .catch() . |
try...catch...finally
Syntaxtry...catch
works only for synchronous errors.finally
for cleanup tasks.error.message
, error.stack
) for debugging.try {
console.log(x); // ReferenceError: x is not defined
} catch (err) {
console.error(err.message);
} finally {
console.log("Cleanup done");
}
throw new Error("message")
over throw "message"
for consistency and debugging.function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (err) {
console.error(err.message);
}
Type | Example |
---|---|
Error |
throw new Error("Custom error") |
SyntaxError |
eval("foo bar") |
ReferenceError |
console.log(x) (x is undefined) |
TypeError |
null.foo() |
RangeError |
new Array(-1) |
URIError |
decodeURIComponent("%") |
eval()
usage to prevent SyntaxError
.Inside async
function (try...catch
)
async function fetchData() {
try {
let res = await fetch("<https://api.example.com/data>");
let data = await res.json();
console.log(data);
} catch (err) {
console.error("Error:", err);
}
}
Async errors in callbacks are not caught
try {
setTimeout(() => { throw new Error("Not caught"); }, 1000);
} catch (err) {
console.error("Won't be caught:", err);
}
Fix: Handle inside the callback