Try/Catch with Async Code
You'll learn why try/catch behaves differently with callbacks, promises, and async/await.
Why Callbacks Break Try/Catch
When you use try/catch with asynchronous callbacks, it won't work as expected. The callback executes after the try block has already finished, so errors escape uncaught:
try {
setTimeout(() => {
throw new Error("This won't be caught!");
}, 100);
} catch (error) {
console.log("Never runs");
}
// Error crashes the program
Think of it like leaving a note for someone to check your mailbox after you've already left the building—you're not there to receive their message.
Try/Catch with Promises
With promises, errors must be caught using .catch() on the promise chain, not with a surrounding try/catch:
// This WON'T catch the error:
try {
Promise.reject(new Error("Oops"));
} catch (error) {
console.log("Doesn't catch it");
}
// Use .catch() instead:
Promise.reject(new Error("Oops"))
.catch(error => console.log("Caught:", error.message));
Try/Catch with Async/Await
Here's the good news: try/catch works perfectly with async/await because await pauses execution inside the try block:
async function fetchData() {
try {
const result = await Promise.reject(new Error("Network failure"));
} catch (error) {
console.log("Caught:", error.message); // ✓ Works!
}
}
fetchData();
async/await makes asynchronous code look synchronous, so try/catch behaves as you'd expect.
Key Takeaway: try/catch doesn't work with callbacks (error happens later), requires .catch() with bare promises, but works naturally with async/await because it waits for promises to resolve inside the try block.