try...catch...finally
syntax
- Error Handling Best Practices
- Throwing Errors:
throw new Error("message")
vs. throw "message"
- Error Object Structure:
name
, message
, stack
try...catch
can be used in synchronous code
try {
let result = 10 / 0;
console.log(result);
} catch (error) {
console.error("Error caught:", error);
}
try...catch
can be used inside an async
function
async function fetchData() {
try {
let response = await fetch("<https://api.example.com/data>");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchData();
try...catch
cannot catch errors inside a callback function if the callback executes asynchronously. The error is thrown asynchronously, so the surrounding try...catch
has already finished execution before the error occurs
try {
setTimeout(() => {
throw new Error("This error won't be caught");
}, 1000);
} catch (error) {
console.error("Caught error:", error); // ❌ This will not work!
}
- Handle Errors in Callbacks
// Use try...catch inside the callback
setTimeout(() => {
try {
throw new Error("This error is caught!");
} catch (error) {
console.error("Caught error:", error);
}
}, 1000);
// Or use Promise-based error handling
function delayedTask() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error("Promise rejection"));
}, 1000);
});
}
delayedTask().catch(error => console.error("Caught error:", error));