How does try/catch work with async/await?

1. Definition

In Node.js, try/catch is used with async/await to handle errors in asynchronous code. It works similar to synchronous error handling, making async code easier to read and manage.

2. How it Works

  • await pauses execution until promise resolves
  • If promise rejects → control goes to catch
  • Errors are handled like synchronous code

3. Example

const fs = require("fs").promises;

async function readFile() {
  try {
    const data = await fs.readFile("file.txt", "utf8");
    console.log(data);
  } catch (err) {
    console.error("Error:", err.message);
  }
}

readFile();

4. Without try/catch (Problem)

async function readFile() {
  const data = await fs.readFile("file.txt", "utf8");
  console.log(data);
}

// ❌ If error occurs → Unhandled Promise Rejection

5. Advantages

  • Clean and readable code
  • Handles async errors like sync code
  • Prevents crashes
  • Better debugging

6. Best Practices

  • Always wrap await inside try/catch
  • Handle specific errors when possible
  • Avoid empty catch blocks