Intro to Asynchronous Programming - Error handling with `try...catch`

Learning objective: By the end of this lesson, students will understand how to use try...catch blocks in JavaScript to handle errors effectively.

What is a try...catch statement?

The try...catch statement lets us handle errors in our code without stopping the entire program.

try

📚 Throwing an error means the code has detected something went wrong and is stopping that part of the program. When this happens inside a try block, the program moves to the catch block to handle it.

catch

Anatomy of try...catch

Let’s look at how a try...catch block is structured:

Anatomy of `try...catch`

  1. The try keyword starts a block of code to run.
  2. Inside the block, we write the code that might cause an error.
  3. The catch keyword starts another block that runs if an error happens.
  4. The error object (also called err, e, or another name) holds details about what went wrong.
  5. In the catch block, we write the code to handle the error.

The purpose of this structure is to allow our program to keep running, even if something goes wrong.

👉 You can read more about how try...catch works in the MDN documentation.

Using try...catch in asynchronous functions

Why do we need try...catch when working with asynchronous code?

Asynchronous operations (like reading a file, fetching data from a server, or connecting to a database) depend on other systems outside your app. These systems might not work the way you expect — for example, a file might be missing or a server might be offline.

Because of this, asynchronous code is more likely to cause errors, so it’s a good idea to use try...catch to handle problems safely.

Example: Reading a file that doesn’t exist

const readAnotherFile = async () => {
  try {
    // This tries to read a file that does not exist
    const data = await fs.readFile('test4.txt', 'utf8');
    console.log(data);
  } catch (error) {
    // This runs if there is an error (like the file not being found)
    console.log(error);
  }
};

readAnotherFile();

What’s happening in this code:

This way, the program doesn’t crash — it handles the error and keeps running.

Run the code

To test it, run the file in your terminal:

node app.js

You will see an error message in your console:

[Error: ENOENT: no such file or directory, open 'test4.txt'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: 'test4.txt'
}

That means the file was not found — but instead of crashing, our code caught the error and printed it.

🧠 Error messages can look complicated, but the first line usually explains the problem clearly. In this case, it says: no such file or directory, open 'test4.txt' This tells us the file test4.txt could not be found.